linux使用管道命令执行ps获取cpu与内存占用率

2019-09-23 09:42:41王冬梅

                               fp ) )
        {
            // 再以空格分隔符拆分字符串
            pcTmp = strtok( caStdOutLine, " " );

            // 用户名跳过,直接匹配 PID ,不匹配跳过
            pcTmp = strtok( NULL, " " );
            if ( 0 != strncasecmp( caSelfPID,
                                   pcTmp,
                                   strlen( caSelfPID ) ) )
            {
                continue;
            }

            // 读出进程自身 CPU 占用率
            pcTmp = strtok( NULL, " " );
            printf( "CPU = %s %%n", pcTmp );

            // 读出进程自身 MEM 占用率
            pcTmp = strtok( NULL, " " );
            printf( "MEM = %s %%n", pcTmp );

            break;
        }

        // 关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。
        // 如果 shell 不能被执行,
        // 则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
        pclose( fp );

    }while ( 0 );
}


$ gcc main.c -o test
$ ./test
CPU = 1.0 %
MEM = 0.0 %

$ ps  aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
nsc      24505  1.0  0.0   2004   232 pts/0    S+   09:46   0:00 ./test