linux 标准流管道 popen 源码理解

标准流管道popen、pclose函数说明:#include FILE *popen(const char *command, const char *type)返回值:若成功,返回文件流指针;若出错,返回-1 参数说明:Command:指向的是一个以 null 结束符结尾的字符串,这个字符串包含一个 shell 命令,并被送到/bin/sh 以-c 参数执行,即由 shel
摘要由CSDN通过智能技术生成

标准流管道popen、pclose函数说明:

#include <stdio.h>
FILE *popen(const char *command, const char *type)

返回值:若成功,返回文件流指针;若出错,返回-1
参数说明:

  • Command:指向的是一个以 null 结束符结尾的字符串,这个字符串包含一个 shell 命令,并被送到/bin/sh 以-c 参数执行,即由 shell 来执行
  • type:
    • ”r”: 文件指针连接到 command 的标准输出
    • “w” :文件指针连接到 command 的标准输入
#include <stdio.h>
int pclose(FILE *stream)

返回值:若成功,返回 popen 中执行命令的终止状态;若出错,返回-1
参数说明:

  • stream:要关闭的文件流

popen函数其实是对管道操作的一些包装,所完成的工作有以下几步:

  • 创建一个管道。
  • fork 一个子进程。
  • 在父子进程中关闭不需要的文件描述符。
  • 执行 exec 函数族调用。
  • 执行函数中所指定的命令。

可以对照着Richard Stevens 实现的源码加深理解。
linux popen源码:

/* 
 *  popen.c     Written by W. Richard Stevens 
 */  

#include    <sys/wait.h>  
#include    <errno.h>  
#include    <fcntl.h>  
#include    "ourhdr.h"  

static pid_t    *childpid = NULL;  
                        /* ptr to array allocated at run-time */  
static int      maxfd;  /* from our open_max(), {Prog openmax} */  

#define SHELL   "/bin/sh"  

FILE *  
popen(const char *cmdstring, const char *type)  
{  
    int     i, pfd[2];  
    pid_t   pid;  
    FILE    *fp;  

            /* only allow "r" or "w" */  
    if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {  
        errno = EINVAL;     /* required by POSIX.2 */  
        return(NULL);  
    }  

    if (childpid == NULL) {     /* first time through */  
                /* allocate zeroed out array for child pids */  
        maxfd = open_max();  
        if ( (childpid = calloc(maxfd, sizeof(pid_t))) == NULL)  
            return(NULL);  
    }  

    if (pipe
  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值