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 */
}