popen从进程中读和写

来源:岁月联盟 编辑:exp 时间:2011-09-07

popen()函数介绍
函数定义
FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );
函数说明
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command 参数是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。
返回值
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
返回错误
popen 没有为内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。
举例:
/* calc.c - calculator front-end which uses bc for everything */
  2 
  3 /* This is a very simple calculator which uses the external bc
  4    command to do everything. It opens a pipe to bc, reads a command
  5    in, passes it to bc, and exits. */
  6 #include <stdio.h>
  7 #include <sys/wait.h>
  8 #include <unistd.h>
  9 
 10 int main(void) {
 11     char buf[1024];
 12     FILE * bc;
 13     int result;
 14 
 15     /* open a pipe to bc, and exit if we fail */
 16     bc = popen("bc", "w");  /*调用linux系统下的计算器函数,并可知是向该计算器进程写入数据*/
 17     if (!bc) {
 18         perror("popen");
 19         return 1;
 20     }
 21 
 22     /* prompt for an expression, and read it in */
 23     printf("expr: "); fflush(stdout);  /*输入的数据立即显示*/
 24     fgets(buf, sizeof(buf), stdin);    /*从标准输入中得到数据*/
 25 
 26     /* send the expression to bc for evaluation */
 27     fprintf(bc, "%s/n", buf);
 28     fflush(bc);
 29 
 30     /* close the pipe to bc, and wait for it to exit */
 31     result = pclose(bc);
 32 
 33     if (!WIFEXITED(result))
 34         printf("(abnormal exit)/n");
 35 
 36     return 0;
}
"calc.c" [已转换] 3
 运行效果如下:
root@ubuntu:~/code# ./calc                                                                                                                        
 
expr: 5*2                                                                                                                                            
 
10
 
root@ubuntu:~/code#
作者 “pstary”