popen()

来源:互联网 发布:xp添加网络win7打印机 编辑:程序博客网 时间:2024/04/30 08:38

popen()函数原型如下:

        FILE *popen(const char *cmd,const char *type);

                                         返回值:若成功返回文件指针,出错则返回NULL

功能:创建一个管道,fork一个子进程,接着关闭管道的不使用端,子进程执行cmd指向的应用程序或者命令。

执行完该函数后父进程和子进程之间生成一条管道,函数返回值为FILE结构指针,该指针作为管道的一端,为父进程所拥有。子进程则拥有管道的另一端,该端口为子进程的stdin或者stdout。如果type=r,那么该管道的方向为:子进程的stdout到父进程的FILE指针;如果type=w,那么管道的方向为:父进程的FILE指针到子进程的stdin。

example:

 主程序popen.c如下所示:

[html] view plaincopy
  1. #include <unistd.h>  
  2. #include <sys/types.h>  
  3. #include <sys/wait.h>  
  4. #include <errno.h>  
  5. #include <stdio.h>  
  6. #include <stdlib.h>  
  7.   
  8. int main()  
  9. {  
  10.     char line[1024];  
  11.     FILE *fpin,*fpout;  
  12.       
  13.     fpin=fopen("in.txt","r");  
  14.       
  15.     fpout=popen("/my_fun","w");  
  16.       
  17.     while(fgets(line,1024,fpin)!=NULL)  //原型是char *fgets(char *s, int n, FILE *stream);   
  18.    //功能:  从文件指针stream中读取n-1个字符,存到以s为起始地址的空间里,直到读完一行,如果成功则返回s的指针,否则返回NULL。
  19.         fputs(line,fpout);  
  20.           
  21.     pclose(fpout);  
  22.     fclose(fpin);  
  23.       
  24.     return 0;  
  25. }  


my_fun.c程序代码如下:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     char line[1024];  
  5.   
  6.     while(fgets(line,1024,stdin)!=NULL)  
  7.         fputs(line,stdout);  
  8.           
  9.     return 0;  


    #include <unistd.h>      #include <sys/types.h>      #include <sys/wait.h>      #include <errno.h>      #include <stdio.h>      #include <stdlib.h>            int main()      {          char line[1024];          FILE *fpin,*fpout;                    fpout=popen("pidof sig_bus","r");                    while(fgets(line,1024,fpout)!=NULL)  //原型是char *fgets(char *s, int n, FILE *stream);                         //功能:  从文件指针stream中读取n-1个字符,存到以s为起始地址的空间里,直到读完一行,如果成功则返回s的指针,否则返回NULL。        printf("sig_bus's pid : %s\n",line);        pclose(fpout);          fclose(fpin);                    return 0;      }  


程序分析如下:首先popen()函数创建一条管道,方向为父进程的fpout到子进程的stdin,接着popen程序打开in.txt文本并一行一行地读取出来写到管道的fpout端。子进程则从stdin中读取从父进程发送过来的数据显示到stdout中。

转自http://blog.csdn.net/myshy025tiankong/article/details/6998288