linux里 popen函数的作用

函数原型:

  #include “stdio.h”

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

        int pclose(FILE *stream_to_close);

参数说明:

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

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

作用:

    popen函数允许一个程序将另外一个程序作为新进程来启动,并可以传递数据或者通过它接受数据。

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

缺点:

    使用popen的不好影响是,针对每个popen调用,不仅要启动一个被请求的程序,还要启动一个shell,即每个popen调用将多启动两个进程。

 举例:

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<string.h>
  4 
  5 int main()
  6 {
  7     FILE *fp=NULL;
  8     FILE *fh=NULL;
  9     char buff[128]={0};
 10 
 11     memset(buff,0,sizeof(buff));
 12     fp=popen("ls -l","r");//将命令ls-l 同过管道读到fp
 13     fh=fopen("shell.c","w+");// 创建一个可写的文件
 14     fread(buff,1,127,fp);//将fp的数据流读到buff中
 15     fwrite(buff,1,127,fh);//将buff的数据写入fh指向的文件中
 16 
 17     pclose(fp);
 18     fclose(fh);
 19 
 20     return 0;
 21 
 22     }
~                                                                               

运行结果:

[lol@localhost practice]$ ls
popen  popen.c  shell.c
[lol@localhost practice]$ cat shell.c
total 12
-rwxrwxr-x. 1 lol lol 5478 May 24 15:39 popen
-rw-rw-r--. 1 lol lol  473 May 24 15:39 popen.c
-rw-rw-r--. 1 lol lol   [lol@localhost practice]$ vim popen.c
[lol@localhost practice]$ 



猜你喜欢

转载自blog.csdn.net/qq_40340448/article/details/80435604
今日推荐