FILE *popen(const char *command, const char *type);
popen()是一个系统函数,它完成fork()产生一个子进程,然后从子进程调用/bin/sh -c(即使用shell)来执行command的指令。父进程通过它得到子进程返回的文件描述符: FILE * popen( const char * command,const char * type);
popen() 函数 用创建管道的方式启动一个进程,并调用 shell.因为管道是被定义成单向的, 所以 type 参数只能定义成只读或者只写, 不能是两者同时, 结果流也相应的是只读或者只写. command 参数是一个字符串指针, 指向的是 一个以 null 结束符结尾的字符串, 这个字符串包含一个 shell 命令. 这个命令被送到 /bin/sh 以 -c 参数 执行, 即由 shell 来执行. type 参数 也是一个 指向以 null 结束符结尾的字符串的指针, 这个字符串必须是'r'或者'w’ 来指明是读还是写. popen() 函数的返回值是一个普通的标准I/O流,它只能用 pclose() 函数来关闭, 而不是 fclose(). 函数. 向这个流的写入被转化为对command命令的标准输入; 而command 命令的标准输出则是和调用 popen(), 函数的进程相同,除非这 被command命令自己改变. 相反的, 读取 一个“被popen了的” 流, 就相当于读取 command 命令的标准输出, 而 command 的 标准输入则是和调用 popen, 函数的进程相同. 注意, popen 函数的输出流默认是被全缓冲的 经验,popen后,就可以用fgetc,fgets,fread,fread进行操作。
#include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; char * buffer; size_t result; pFile = popen ( "ls -l" , "r" ); if (pFile==NULL) {fputs ("File error",stderr); exit (1);} buffer = (char*) malloc (1024); if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} result = fread (buffer,1,lSize,pFile); printf("%s/n",buffer); fclose (pFile); free (buffer); return 0; }
1024

被折叠的 条评论
为什么被折叠?



