popen、system

一、popen函数

功   能:   创建管道I/O(创建管道的方式启动一个进程)

头文件#include <stdio.h>

函数声明FILE * popen(const char * command,const char * type);

函数说明popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh/ -c 来执行参数command的指令。参数type可使用“r“表示读,”w“表示写入,按照这个type值,popen()会建立管道连到子进程的标准输入或输出上,然后返回一个文件指针。然后进程就可以利用这个文件指针来读取子进程的输出或是写入的进程的标准输入中。此外,所有使用文件指针(FILE*)的函数也都可以使用,除了fclose()。只能用pclose()进行关闭

返回值成功返文件指针,否则返回NULL,错误原因存于errno中。

错误代码EINVAL  参数type不合法

代码实现

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<unistd.h>
  5 #include<sys/types.h>
  6 
  7 int main()
  8 {
  9         FILE *strem;   
 10         FILE *wstrem;
 11         char buf[100];
 12         memset(buf,0x00,sizeof(buf)); //初始化buf
 13         strem=popen("ls -l","r");  //将ls -l 命令输出通过管道 读到strem里面
 14         wstrem=fopen("a.text","w");  // 打开一个可写的文件
 15         fread(buf,sizeof(char),sizeof(buf),strem); //从strem 中读数据到 buf 中 
 16         fwrite(buf,1,sizeof(buf),wstrem); //将buf中的数据写到wstrem中
 17         pclose(strem);
 18         fclose(wstrem);
 19 
 20 }
~    

二、system函数

头文件      : #include <stdlib.h>

函数声明   :int system(const char *command);

功       能   :system()函数先fork一个子进程,在这个子进程中调用/bin/sh -c来执行command指定的命令。/bin/sh在系统中一般是个软链接,指向dash或者bash等常用的shell,-c选项是告诉shell从字符串command中读取要执行的命令(shell将扩展command中的任何特殊字符)。父进程则调用waitpid()函数来为变成僵尸的子进程收尸,获得其结束状态,然后将这个结束状态返回给system()函数的调用者。



猜你喜欢

转载自blog.csdn.net/z_juan1/article/details/81006289
今日推荐