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);
}