popen()

本文详细介绍了popen函数的使用方法及实例,展示了如何通过popen建立管道进行进程间通信,并给出了具体的C语言代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.youkuaiyun.com/myshy025tiankong/article/details/6998288
03-14
### Python `Popen` 使用方法及示例 #### 创建子进程并与其交互 为了创建一个新的进程并与之通信,可以使用 `subprocess.Popen` 类。此类提供了灵活性来管理子进程的标准输入、标准输出以及错误流。 ```python from subprocess import Popen, PIPE # 启动一个外部命令并将stdout和stderr重定向到PIPE proc = Popen(['echo', 'Hello World'], stdout=PIPE, stderr=PIPE) # 获取命令执行后的返回结果 output, error = proc.communicate() print(f'Output: {output.decode()}') if error: print(f'Error: {error.decode()}') ``` 上述代码展示了如何启动一个简单的命令,并通过管道读取其输出[^2]。 #### 设置参数传递给构造器 当实例化 `Popen` 对象时,可以通过向构造函数提供不同的参数来自定义行为: - **args**: 要运行的命令及其参数列表或者字符串形式。 - **bufsize**: 缓冲区大小;默认情况下为0(无缓冲),可设置为1表示行缓存或负数代表全缓冲。 - **executable**: 可选字段用于指定要执行的实际文件路径,在某些平台上可能有用。 - **stdin**, **stdout**, 和 **stderr**: 控制子进程中这些流的行为,默认值通常就足够用了。 - **preexec_fn/pre creation flags/startupinfo/close_fds**: 平台特定选项,允许更细粒度控制新进程属性。 更多细节可以在官方文档中找到关于各个平台的支持情况说明。 #### 实际应用场景举例 假设有一个场景是要调用 Git 来获取当前分支名称: ```python import subprocess def get_current_git_branch(): try: process = subprocess.Popen( ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=subprocess.PIPE, universal_newlines=True ) output = process.stdout.read().strip() exit_code = process.wait(timeout=5) if exit_code != 0: raise Exception('Failed to retrieve git branch.') return output except FileNotFoundError as e: raise Exception('Git not installed or repository does not exist.') from e branch_name = get_current_git_branch() print(branch_name) ``` 这段脚本演示了怎样安全地处理潜在异常,并且合理利用超时机制防止无限等待子进程完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值