理论:
库函数: popen();
函数声明: FILE *popen ( char *command, char *type);
返回值: new file stream on success
NULL on unsuccessful fork() or pipe() call
NOTES: creates a pipe, and performs fork/exec operations using "command"
popen()函数首先调用pipe()函数建立一个管道,然后它用fork()函数建立一个子进程,
运行一个shell 环境,然后在这个shell 环境中运行"command"参数指定的程序。数据在管道
中流向由"type"参数控制。这个参数可以是"r"或者"w",分别代表读和写。需要注意的是,
"r"和"w"两个参数不能同时使用!在Linux 系统中,popen 函数将只使用"type"参数中第一
个字符,也就是说,使用"rw"和"r"作为"type"参数的效果是一样的,管道将只打开成读状态。
使用popen 打开的管道必须用pclose()函数来关闭。还记得fopen 和fclose 的配对使用
吗?这里再次显示了管道和文件的相似性。
mode: 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到 command 的标准输入。
库函数: pclose();
函数声明: int pclose( FILE *stream );
返回值: exit status of wait4() call
-1 if "stream" is not valid, or if wait4() fails
NOTES: waits on the pipe process to terminate, then closes the stream.
---------------------------------------
注意:管道是在 pclose() 的时候执行 popen() 创建的脚本命令
简单例子
---------------------------------------
// test.c
#include <stdio.h>
#define MAXSTRS 5
int main(void)
{
int cntr;
FILE *pipe_fp;
char *strings[MAXSTRS] = { "roy", "zixia", "gouki","supper", "mmwan"};
/* 用popen 建立管道 */
if (( pipe_fp = popen("sort", "w")) == NULL)
{
perror("popen");
exit(1);
}
/* Processing loop */
for(cntr=0; cntr<MAXSTRS; cntr++)
{
fputs(strings[cntr], pipe_fp);
fputc('\n', pipe_fp);
}
/* 关闭管道 */
pclose(pipe_fp);
return(0);
}
---------------------------------------
编译 cc -o test test.c
执行 ./test
---------------------------------------
使用popen()函数除了节省源代码之外,它还有一个优点:你可以在"command"中使用
任意合法的shell 指令,包括重定向和管道!下面的几个例子都是合法的popen 调用:
popen("ls ~roy", "r");
popen("sort > /tmp/zixia", "w");
popen("sort | uniq | more", "w");
下面是一个稍微复杂一点的例子,在里面建立了两个管道:
稍微复杂的例子
---------------------------------------
// test2.c
#include <stdio.h>
int main(void)
{
FILE *pipein_fp, *pipeout_fp;
char readbuf[80];
/* 用popen 建立一个通向"ls:的读管道 */
if (( pipein_fp = popen("ls", "r")) == NULL)
{
perror("popen");
exit(1);
}
/* 用popen 建立一个通向"sort"的写管道 */
if (( pipeout_fp = popen("sort", "w")) == NULL)
{
perror("popen");
exit(1);
}
/* 进程循环 */
while(fgets(readbuf, 80, pipein_fp))
fputs(readbuf, pipeout_fp);
/* 关闭打开的管道 */
pclose(pipein_fp);
pclose(pipeout_fp);
return(0);
}
-----------------------------------------
编译 cc -o test2 test2.c
执行 ./test2
popen和pclose函数
最新推荐文章于 2024-05-15 04:31:31 发布