首页 > 系统 > Linux > 正文

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

2019-10-26 18:38:46
字体:
来源:转载
供稿:网友

代码如下:
#include <stdio.h>
#include <unistd.h>
int main()
{
    char caStdOutLine[1024]; // ps 命令的标准输出中的一行信息
    char* pcTmp = NULL;      // 指向以空格拆分后的字符串

    char caSelfPID[10];      // 自身进程的PID字符串
    char caPSCmd[24];        // "ps aux | grep PID"命令字符串

    memset( caSelfPID, 0, sizeof( caSelfPID ) );
    sprintf( caSelfPID,
             "%d",
             getpid() );

    memset( caPSCmd, 0, sizeof( caPSCmd ) );
    sprintf( caPSCmd,
             "ps aux | grep %d",
             getpid() );

    do // 非循环,只是为了方便控制分支层次,便于控制分支流向
    {
        // 通过创建一个管道,调用 fork 产生一个子进程,
        // 执行一个 shell 以运行命令来开启一个进程。
        // 这个进程必须由 pclose() 函数关闭。
        FILE* fp = popen( caPSCmd, // 一个指向以 NULL 结束的 shell 命令字符串的指针,
                                   // 这行命令将被传到 bin/sh 并使用 -c 标志,
                                   // 那么 shell 将执行这个命令从这个字符串中读取。
                          "r" );   // 文件指针连接到 shell 命令的标准输出

        if ( NULL == fp )
        {
            printf( "call popen is failed/n" );
            break;
        }

        memset( caStdOutLine, 0, sizeof( caStdOutLine ) );
        while ( NULL != fgets( caStdOutLine,
                               sizeof( caStdOutLine ),

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表