popen()


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如下所示:

  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程序代码如下:

  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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值