#include stdio.h>
#include unistd.h>
int main()
{
char caStdOutLine[1024]; // ps 命令的標(biāo)準(zhǔn)輸出中的一行信息
char* pcTmp = NULL; // 指向以空格拆分后的字符串
char caSelfPID[10]; // 自身進(jìn)程的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 // 非循環(huán),只是為了方便控制分支層次,便于控制分支流向
{
// 通過(guò)創(chuàng)建一個(gè)管道,調(diào)用 fork 產(chǎn)生一個(gè)子進(jìn)程,
// 執(zhí)行一個(gè) shell 以運(yùn)行命令來(lái)開(kāi)啟一個(gè)進(jìn)程。
// 這個(gè)進(jìn)程必須由 pclose() 函數(shù)關(guān)閉。
FILE* fp = popen( caPSCmd, // 一個(gè)指向以 NULL 結(jié)束的 shell 命令字符串的指針,
// 這行命令將被傳到 bin/sh 并使用 -c 標(biāo)志,
// 那么 shell 將執(zhí)行這個(gè)命令從這個(gè)字符串中讀取。
"r" ); // 文件指針連接到 shell 命令的標(biāo)準(zhǔn)輸出
if ( NULL == fp )
{
printf( "call popen is failed\n" );
break;
}
memset( caStdOutLine, 0, sizeof( caStdOutLine ) );
while ( NULL != fgets( caStdOutLine,
sizeof( caStdOutLine ),
fp ) )
{
// 再以空格分隔符拆分字符串
pcTmp = strtok( caStdOutLine, " " );
// 用戶名跳過(guò),直接匹配 PID ,不匹配跳過(guò)
pcTmp = strtok( NULL, " " );
if ( 0 != strncasecmp( caSelfPID,
pcTmp,
strlen( caSelfPID ) ) )
{
continue;
}
// 讀出進(jìn)程自身 CPU 占用率
pcTmp = strtok( NULL, " " );
printf( "CPU = %s %%\n", pcTmp );
// 讀出進(jìn)程自身 MEM 占用率
pcTmp = strtok( NULL, " " );
printf( "MEM = %s %%\n", pcTmp );
break;
}
// 關(guān)閉標(biāo)準(zhǔn) I/O 流,等待命令執(zhí)行結(jié)束,然后返回 shell 的終止?fàn)顟B(tài)。
// 如果 shell 不能被執(zhí)行,
// 則 pclose() 返回的終止?fàn)顟B(tài)與 shell 已執(zhí)行 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