zl程序教程

您现在的位置是:首页 >  工具

当前栏目

学习笔记——popen()函数详解

笔记学习 详解 函数 popen
2023-09-11 14:16:59 时间

popen()函数

引用度娘说的:
popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程

这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。

也就是,popen创建管道,执行shell命令将文件流中的某些数据读出

看看man手册


NAME
       popen, pclose - pipe stream to or from a process
      

SYNOPSIS


       #include <stdio.h>//头文件

      FILE *popen(const char *command, const char *type);//原型

参数说明:

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

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

返回值
如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回一个读或者打开文件的指针。

接下来看看demo

#include <stdio.h>
#include <unistd.h>

int main(int argc ,char **argv){
	
	char ret[1024] = {0};
	FILE *fp;

	//FILE *popen(const char *command, const char *type);
	fp = popen("ls -l","r");

	//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
	int nread = fread(ret,1,1024,fp);
	printf("read ret %d byte, %s\n",nread,ret);
	
	return 0;
}

这个demo很好的验证了通过管道输出的情况,通过调用popen去执行ls -l命令,把结果给fp,通过fread读取。所以,popen和system的表面区别在于system执行之后直接把结果显示了,而不能去进行读或者写

结果如下:
把read ret 1024 byte, total 140打印了出来,还显示了全部文件信息

在这里插入图片描述
ending!!!