#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$