标准流管道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