popen函数
来源:互联网 发布:软件部署实施方案 编辑:程序博客网 时间:2024/05/17 23:56
我们平时写程序和用终端输入命令的时候,常常会用到管道,比如,在一段程序中,你可能会这样写
int fd[2]; pipe(fd)
这时,我们就创建了一个管道,实现了进程之间的通信。
再比如,我们用终端的时候,我们可能会这样输入命令: ls -la | grep test
我们也是在两个命令之间创建了一个管道。
这篇文章介绍一个函数,用来创建管道的函数:popen
首先,我们先看看 man page 给的函数原型:
#include
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
下面看看一段测试程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* popen_main.c
*
* Created on: 2013年11月28日
* Author: DLUTBruceZhang
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF_LEN
4096
int
main(
int
argc,
char
**argv,
char
**environ)
{
char
*buf = NULL;
buf = (
char
*)malloc(sizeof(
char
) * MAX_BUF_LEN);
FILE *file = popen(
"ls -la"
,
"r"
);
/*子进程执行 ls -la ,并把输出写入管道中*/
memset(buf,
0
, sizeof(buf));
while
(!feof(file))
{
fgets(buf, MAX_BUF_LEN, file);
/*另一个进程读取管道中的内容*/
printf(
"%s"
, buf);
}
pclose(file);
free(buf);
return
0
;
}
</string.h></stdlib.h></stdio.h>
首先,我用 popen 创建了一个管道,并执行了一个命令 “ls -la”, popen函数会调用 fork 和 pipe,所以,这个命令是一个子进程执行的,由于管道之间的共享可以发生在父子进程之间,所以,命令的输出可以由父进程读取,之后显示出来,下面的就是这段程序的输出:
1
2
3
4
5
6
7
8
总用量
32
drwxrwxr-x
3
administrator administrator
4096
2013
-
11
-
28
09
:
58
.
drwxrwxr-x
13
administrator administrator
4096
2013
-
11
-
28
09
:
58
..
-rw-rw-r--
1
administrator administrator
10812
2013
-
11
-
28
09
:
58
.cproject
drwxrwxr-x
2
administrator administrator
4096
2013
-
11
-
28
10
:
05
Debug
-rw-rw-r--
1
administrator administrator
487
2013
-
11
-
28
10
:
05
popen_main.c
-rw-rw-r--
1
administrator administrator
762
2013
-
11
-
28
09
:
58
.project
-rw-rw-r--
1
administrator administrator
762
2013
-
11
-
28
09
:
58
.project
阅读全文
0 0
- popen 函数
- popen函数
- popen函数
- popen()函数
- popen函数
- 函数popen()
- Popen函数
- popen函数
- 函数popen
- 函数popen()
- popen 函数
- popen函数
- popen函数
- linux popen函数
- popen函数的介绍!
- 自己实现popen函数
- unp pipe popen函数
- popen函数详解
- php和java之间aes加密的互通
- CCF201312-1 出现次数最多的数 桶排序
- @Cacheable注解在spring3中的使用-实现缓存
- ArrayList源码(2)
- JQuery教程详解二之JQuery效果
- popen函数
- html_day04_字符实体
- [UVa1626]括号序列
- 利用边框制作三角形
- python和java中斜杠的写法及区分
- PAT 1008数组元素循环右移
- raspberry pi 2安装rtl8811/ 8821网卡驱动
- 极乐小程序榜单(第三期)
- LeetCode 232 Implement Queue using Stacks(利用栈实现队列)