popen() 使用举例 (转载)

函数原型:

  #include “stdio.h”

  FILE *popen( const char* command, const char* mode )

  参数说明:

  command: 是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用 -c 标志,shell 将执行这个命令。

  mode: 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到 command 的标准输入。

  返回值:

  如果调用成功,则返回一个读或者打开文件的指针,如果失败,返回NULL,具体错误要根据errno判断

  int pclose (FILE* stream)

  参数说明:

  stream:popen返回的文件指针

  返回值:

  如果调用失败,返回 -1

  作用:

  popen() 函数用于创建一个管道:其内部实现为调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程这个进程必须由 pclose() 函数关闭。

  例子:

  管道读:先创建一个文件test,然后再test文件内写入“Read pipe successfully !”

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int main(void)  
  5. {  
  6.     FILE *fp;  
  7.     char buf[1024] =   { 0 };  
  8.   
  9.   
  10.     if ((fp = popen("cat test", "r")) == NULL)  
  11.     {  
  12.         perror("Fail to popen ");  
  13.         exit(1);  
  14.     }  
  15.   
  16.     while (fgets(buf, 200, fp) != NULL)  
  17.     {  
  18.         printf("%s ",buf);  
  19.     }  
  20.     pclose(fp);  
  21.     return EXIT_SUCCESS;  
  22. }  


管道写:

  1. #include “stdio.h”  
  2.   
  3.   #include “stdlib.h”  
  4.   
  5.   int main()  
  6.   
  7.   {  
  8.   
  9.   FILE *fp;  
  10.   
  11.   char buf[200] = {0};  
  12.   
  13.   if((fp = popen(“cat > test1″, “w”)) == NULL) {  
  14.   
  15.   perror(“Fail to popen ”);  
  16.   
  17.   exit(1);  
  18.   
  19.   }  
  20.   
  21.   fwrite(“Read pipe successfully !”, 1, sizeof(“Read pipe successfully !”), fp);  
  22.   
  23.   pclose(fp);  
  24.   
  25.   return 0;  
  26.   
  27.   }  


执行完毕后,当前目录下多了一个test1文件,打开,里面内容为Read pipe successfully !

转载自:http://blog.csdn.net/ningxiaowei2013/article/details/25819077

原文地址:https://www.cnblogs.com/Demo1589/p/7845658.html