函数popen()

来源:互联网 发布:才真旺姆解释双修 知乎 编辑:程序博客网 时间:2024/05/21 08:39

转载:http://blog.csdn.net/qian_f/article/details/8227435

函数说明

  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。


用到popen()的时候,到网上找了找,发现网上好多对man帮助里的内容进行了解释,有部分解释内容如下:“popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。前面提到这个流是单向的。所以向这个流写内容相当于写入该命令的标准输入;命令的标准输出和调用 popen 的进程相同。与之相反的,从流中读数据相当于读取命令的标准输出;命令的标准输入和调用 popen 的进程相同。”这话怎么读都别扭,理解起来就有些难了。先来看看popen的函数声明:FILE * popen(const char* command, const char* type)

在使用这个函数的时候,将参数type写成“w”就出现了不能理解的地方(网上的一些程序参数type多是“r”)。看下面一个程序:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.         FILE * fp;  
  5.         char buf[40] = {0};  
  6.         fp = popen(NULL, "w");  
  7.         if(NULL == fp)  
  8.         {  
  9.                 perror("popen error.\n");  
  10.                 return -1;  
  11.         }  
  12.         printf("Input command:");  
  13.         fgets(buf, 40, stdin);  
  14.         fputs(buf, fp);  
  15.         pclose(fp);  
  16.         return 0;  
  17. }  

执行结果:

[root@localhost codetest]# ./a.out 
sh: -c: option requires an argument
Input command:pwd

很明显出错了,但是根据那段翻译的内容,搞得自己很糊涂,后来问了老师,说是type参数为"w"的时候,popen的第一个参数为命令解释器,即bash/sh之类。修改后的程序如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.         FILE * fp;  
  5.         char buf[40] = {0};  
  6.         fp = popen("bash""w");  
  7.         if(NULL == fp)  
  8.         {  
  9.                 perror("popen error.\n");  
  10.                 return -1;  
  11.         }  
  12.         printf("Input command:");  
  13.         fgets(buf, 40, stdin);  
  14.         fputs(buf, fp);  
  15.         pclose(fp);  
  16.         return 0;  
  17. }  
执行结果:

[root@localhost codetest]# ./a.out 
Input command:pwd
/home/qian/codetest

这下就对了!

可是还是有疑问的,如果我直接在popen()的第一个参数写命令,也同样可以得到命令结果,程序如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.         FILE * fp;  
  5.         char buf[40] = {0};  
  6.         fp = popen("pwd""w");  
  7.         if(NULL == fp)  
  8.         {  
  9.                 perror("popen error.\n");  
  10.                 return -1;  
  11.         }  
  12.         pclose(fp);  
  13.         return 0;  
  14. }  
执行结果:

[root@localhost codetest]# ./a.out 
/home/qian/codetest

关于这个参数的问题,一直是个疙瘩,如果谁知道的话,可以给个解答,感激不尽!


下面是type参数为“r”的一个程序:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.         FILE * fp;  
  5.         char buf[20] = {0};  
  6.         fp = popen("ls","r");  
  7.         if(NULL == fp)  
  8.         {  
  9.                 perror("popen error!\n");  
  10.                 return -1;  
  11.         }  
  12.         while(fgets(buf, 20, fp) != NULL)  
  13.         {  
  14.                 printf("%s", buf);  
  15.         }  
  16.         pclose(fp);  
  17.         return 0;  
  18. }  

值得注意的是:一定要用pclose()来关闭文件指针,这是我老忘记的事。


下面给出一个网上给出的popen()和pclose()实现函数:

[cpp] view plain copy
  1. Figure 15.12. The popen and pclose functions  
  2. #include "apue.h"  
  3. #include <errno.h>  
  4. #include <fcntl.h>  
  5. #include <sys/wait.h>  
  6.   
  7. /* 
  8.  * Pointer to array allocated at run-time. 
  9.  */  
  10. static pid_t    *childpid = NULL;  
  11.   
  12. /* 
  13.  * From our open_max(), Figure 2.16. 
  14.  */  
  15. static int      maxfd;  
  16.   
  17. FILE *  
  18. popen(const char *cmdstring, const char *type)  
  19. {  
  20.     int     i;  
  21.     int     pfd[2];  
  22.     pid_t   pid;  
  23.     FILE    *fp;  
  24.   
  25.     /* only allow "r" or "w" */  
  26.     if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {  
  27.         errno = EINVAL;     /* required by POSIX */  
  28.         return(NULL);  
  29.     }  
  30.   
  31.     if (childpid == NULL) {     /* first time through */  
  32.         /* allocate zeroed out array for child pids */  
  33.         maxfd = open_max();  
  34.         if ((childpid = calloc(maxfd, sizeof(pid_t))) == NULL)  
  35.             return(NULL);  
  36.     }  
  37.   
  38.     if (pipe(pfd) < 0)  
  39.         return(NULL);   /* errno set by pipe() */  
  40.   
  41.     if ((pid = fork()) < 0) {  
  42.         return(NULL);   /* errno set by fork() */  
  43.     } else if (pid == 0) {                           /* child */  
  44.         if (*type == 'r') {  
  45.             close(pfd[0]);  
  46.             if (pfd[1] != STDOUT_FILENO) {  
  47.                 dup2(pfd[1], STDOUT_FILENO);  
  48.                 close(pfd[1]);  
  49.             }  
  50.         } else {  
  51.             close(pfd[1]);  
  52.             if (pfd[0] != STDIN_FILENO) {  
  53.                 dup2(pfd[0], STDIN_FILENO);  
  54.                 close(pfd[0]);  
  55.             }  
  56.         }  
  57.   
  58.         /* close all descriptors in childpid[] */  
  59.         for (i = 0; i < maxfd; i++)  
  60.             if (childpid[i] > 0)  
  61.                 close(i);  
  62.   
  63.         execl("/bin/sh""sh""-c", cmdstring, (char *)0);  
  64.         _exit(127);  
  65.     }  
  66.   
  67.     /* parent continues... */  
  68.     if (*type == 'r') {  
  69.         close(pfd[1]);  
  70.         if ((fp = fdopen(pfd[0], type)) == NULL)  
  71.             return(NULL);  
  72.     } else {  
  73.         close(pfd[0]);  
  74.         if ((fp = fdopen(pfd[1], type)) == NULL)  
  75.             return(NULL);  
  76.     }  
  77.   
  78.     childpid[fileno(fp)] = pid; /* remember child pid for this fd */  
  79.     return(fp);  
  80. }  
  81.   
  82.   
  83. int  
  84. pclose(FILE *fp)  
  85. {  
  86.     int     fd, stat;  
  87.     pid_t   pid;  
  88.   
  89.     if (childpid == NULL) {  
  90.         errno = EINVAL;  
  91.         return(-1);     /* popen() has never been called */  
  92.     }  
  93.   
  94.     fd = fileno(fp);  
  95.     if ((pid = childpid[fd]) == 0) {  
  96.         errno = EINVAL;  
  97.         return(-1);     /* fp wasn't opened by popen() */  
  98.     }  
  99.   
  100.     childpid[fd] = 0;  
  101.     if (fclose(fp) == EOF)  
  102.         return(-1);  
  103.   
  104.     while (waitpid(pid, &stat, 0) < 0)  
  105.         if (errno != EINTR)  
  106.             return(-1); /* error other than EINTR from waitpid() */  
  107.   
  108.     return(stat);   /* return child's termination status */  
  109. }  
0 0
原创粉丝点击