如下程序的功能是打印名为test的程序的pid。
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp = popen("ps -e | grep \'test\' | awk \'{print $1}\'", "r");//打开管道,执行shell 命令
char buffer[10] = {0};
while (NULL != fgets(buffer, 10, fp)) //逐行读取执行结果并打印
{
printf("PID: %s", buffer);
}
pclose(fp); //关闭返回的文件指针,注意不是用fclose
}