#include <stdio.h>
int main(void){
FILE *fp;
char *cmd="ps";
char line[1024];
//完成fork(),使用shell执行命令,父进程通过它得到子进程返回的文件描述符,popen简化管道操作
fp=popen(cmd,"r");
if (!fp){
perror("打开管道");
exit(1);
}
while (fgets(line,1024,fp)){
printf("%s",line);
}
return 0;
}
deepfuture@deepfuture-laptop:~/private/mytest$ gcc -o testpopen testpopen.c
testpopen.c: In function ‘main’:
testpopen.c:11: warning: incompatible implicit declaration of built-in function ‘exit’
deepfuture@deepfuture-laptop:~/private/mytest$ ./testpopen
PID TTY TIME CMD
2062 pts/0 00:00:00 bash
11929 pts/0 00:00:00 testpopen
11930 pts/0 00:00:00 sh
11931 pts/0 00:00:00 ps
deepfuture@deepfuture-laptop:~/private/mytest$
本文介绍了一个简单的C程序,该程序利用popen函数执行外部命令并读取其输出。通过示例展示了如何使用popen和fgets来获取命令ps的输出,并在屏幕上打印这些信息。

被折叠的 条评论
为什么被折叠?



