C语言popen创建管道文件循环执行shell命令

来源:互联网 发布:java 流程图框架 编辑:程序博客网 时间:2024/06/07 11:08

FILE* popen (const char* command , const char * type );int pclose ( FILE* stream );

popen()函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。
type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
command 参数是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用-c 标志,shell 将执行这个命令。
popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。

#include <stdio.h>#include <string.h>#include <fcntl.h>#define SIZE 128int main(){FILE *fp;char buffer[SIZE];char cmd_str[SIZE];char flag[3];do{memset(buffer,'\0',SIZE);printf("input cmd:");fflush(stdout);fgets(cmd_str,SIZE,stdin);fp=popen(cmd_str,"r");fread(buffer,SIZE,1,fp);printf("%s\n",buffer);pclose(fp);printf("====================\n");printf("<y or n>---->");fgets(flag,3,stdin);}while(strcmp(flag,"y\n")==0);}


原创粉丝点击