Linux popen()函数实现流重定向
popen()函数用法小结:
1)原型是:FILE *popen(char *command,char *modes);
2)返回值:如果成功的话返回一个文件指针,出错的话返回NULL;
3)功能:首先它会创建一个管道,再调用fork()函数创建一个子进程,接着关闭管道的不使用端,也就是在父进程与子进程间建立一个管道,子进程执行command指向的应用程序或者是命令。函数执行成功的返回值FILE结构指针作为管道的一端,为父进程所拥有。子进程则拥有管道的另一端,该端口为子进程的stdin或者stdout。如果modes=r,那么该管道的方向为:子进程的stdout到父进程的FILE指针;如果modes=w,那么管道的方向为:父进程的FILE指针到子进程的stdin。
源代码如下:
#include<stdio.h>
#include<unistd.h>
#include<limits.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
FILE *finput,*foutput;
char buf[PIPE_BUF];
int n;
finput=popen("echo test!","r");
foutput=popen("cat","w");
read(fileno(finput),buf,strlen("test!"));
write(fileno(foutput),buf,strlen("test!"));
pclose(finput);
pclose(foutput);
printf("\n");
exit(EXIT_SUCCESS);
}