您的位置:首页 > 运维架构 > Linux

linux 进程间管道通讯 popen以及pclose

2015-01-04 16:31 323 查看
popen和pclose函数

================================================

 一个常用的操作就是给一个进程创建管道,通过管道读取它的标准输出以及向它的标准输入发送数据,标准输入输出库提供过一个popen以及pclose函数,这两个函数处理了我们需要的所有细节工作:创建管道,创建子进程,关闭无用管道端,执行shell运行命令,并且等待命令结束。

 #include <stdio.h>

 FILE *popen(const char *cmdstring, const char *type);

 返回:如果成功返回文件指针,如果错误返回NULL。

 int pclose(FILE *fp);

 返回:返回命令cmdstring的终止状态,或者如果错误就返回1。

调用popen返回的FILE * 的文件描述符可以调用接口 fwrite以及fread 进行读写操作。

进行读操作

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

int main()

{

   FILE *read_fp;

   char buffer[BUFSIZ +1];

   int chars_read;

   memset(buffer,'\0',sizeof(buffer));

   read_fp = popen("uname -a","r");

   if(read_fp != NULL)

   {

      chars_read = fread(buffer, sizeof(char),BUFSIZ,read_fp);

      if(chars_read > 0)

      {

         printf("Output was : -\n%s\n",buffer);

      }

      pclose(read_fp);

      exit(EXIT_SUCCESS);

   }

   exit(EXIT_FAILURE);

}

进行写操作:

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

int main()

{

   FILE *read_fp;

   char buffer[BUFSIZ +1];

   int chars_read;

   memset(buffer,'\0',sizeof(buffer));

   read_fp = popen("od -c","w");

   if(read_fp != NULL)

   {

      sprintf(buffer, "Once upon a time, there was ...\n");

      fwrite(buffer, sizeof(char),strlen(buffer),read_fp);

      pclose(read_fp);

      exit(EXIT_SUCCESS);

   }

   exit(EXIT_FAILURE);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux