popen获取命令执行结果分析

    C工作者经常遇到需要在C程序中执行shell命令并获取返回结果的情况,一般我们用popen函数来完成,程序如下

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int get_pipeStr(char* cmd, char *res)
{
	int len = 0;

	if(strlen(cmd) <= 0)
		return len;

	FILE *fp = NULL;
	char buff[2048];
	memset(buff, 0, 2048);

	if( (fp = popen(cmd, "r")) == NULL )
		return len;

	while( (fgets(buff, sizeof(buff), fp)) != NULL )
	{
		strcat(res, buff);

        if (strlen(res) > 2000)
            break;
	}

	pclose(fp);

	return strlen(res);
}

      为什么popen函数可以完成此项任务? 我们来看看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) {   
        maxfd = open_max();  
        if ( (childpid = calloc(maxfd, sizeof(pid_t))) == NULL)  
            return(NULL);  
    }  

    if (pipe(pfd) < 0)  //创建管道,pfd[0]-读端  pfd[1]--写端
        return(NULL); 

    if ( (pid = fork()) < 0)   //创建子进程
        return(NULL); 
    else if (pid == 0) {                            /* child */  
        if (*type == 'r') {  //用户想通过父进程读取结果,则子进程负责写端
            close(pfd[0]);     //关闭读端
            if (pfd[1] != STDOUT_FILENO) {  
                dup2(pfd[1], STDOUT_FILENO); //将管道写端绑定到标准输出上  
                close(pfd[1]);  
            }  
        } else {              //用户想通过父进程写入内容,则子进程负责读端
            close(pfd[1]);   //关闭写端
            if (pfd[0] != STDIN_FILENO) { 
                dup2(pfd[0], STDIN_FILENO);  //将管道读端绑定到标准输入中
                close(pfd[0]);  
            }  
        }  
            /* close all descriptors in childpid[] */  
        for (i = 0; i < maxfd; i++)  
            if (childpid[ i ] > 0)  
                close(i);  

        execl(SHELL, "sh", "-c", cmdstring, (char *) 0);  //执行命令
        _exit(127);  
    }  
                                /* parent */  
    if (*type == 'r') {  //用户想通过父进程读取结果,则父进程负责读端
        close(pfd[1]);  
        if ( (fp = fdopen(pfd[0], type)) == NULL)  //将一个IO流绑定到管道读端
            return(NULL);  
    } else {  //用户想通过父进程写入内容,则父进程负责写端
        close(pfd[0]);  
        if ( (fp = fdopen(pfd[1], type)) == NULL)   //将一个IO流绑定到管道写端
            return(NULL);  
    }  

    childpid[fileno(fp)] = pid; /* remember child pid for this fd */  

    return(fp);  //将IO流操作句柄返回给用户
}  

int  pclose(FILE *fp)  
{  

    int     fd, stat;  
    pid_t   pid;  

    if (childpid == NULL)  
        return(-1);     /* popen() has never been called */  

    fd = fileno(fp);  
    if ( (pid = childpid[fd]) == 0)  
        return(-1);     /* fp wasn't opened by popen() */  

    childpid[fd] = 0;  
    if (fclose(fp) == EOF)  
        return(-1);  

    while (waitpid(pid, &stat, 0) < 0)  
        if (errno != EINTR)  
            return(-1); /* error other than EINTR from waitpid() */  

    return(stat);   /* return child's termination status */  
}  

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值