linux popen用法详解
来源:互联网 发布:数据新闻栏目 编辑:程序博客网 时间:2024/06/04 20:08
http://linux.chinaitlab.com/c/806015.html
函数原型:
#include “stdio.h”
FILE *popen( const char* command, const char* mode )
参数说明:
command: 是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用 -c 标志,shell 将执行这个命令。
mode: 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到command 的标准输入。
返回值:
如果调用成功,则返回一个读或者打开文件的指针,如果失败,返回NULL,具体错误要根据errno判断
int pclose (FILE* stream)
参数说明:
stream:popen返回的文件指针
返回值:
如果调用失败,返回 -1
作用:
popen() 函数用于创建一个管道:其内部实现为调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程这个进程必须由 pclose() 函数关闭。
例子:
管道读:先创建一个文件test,然后再test文件内写入“Readpipe successfully !”
#include “stdio.h”
#include “stdlib.h”
int main()
{
FILE *fp;
char buf[200] = {0};
if((fp = popen(“cat test”, “r”)) == NULL) {
perror(“Fail to popen\n”);
exit(1);
}
while(fgets(buf, 200, fp) != NULL) {
printf(“%s”, buf);
}
pclose(fp);
return 0;
}
打印输出: Read pipe successfully !
管道读:
#include “stdio.h”
#include “stdlib.h”
int main()
{
FILE *fp;
char buf[200] = {0};
if((fp = popen(“cat > test1″, “w”)) == NULL) {
perror(“Fail to popen\n”);
exit(1);
}
fwrite(“Read pipe successfully !”, 1, sizeof(“Read pipe successfully!”), fp);
pclose(fp);
return 0;
}
执行完毕后,当前目录下多了一个test1文件,打开,里面内容为Read pipe successfully !
- linux popen用法详解
- Linux popen用法
- Linux popen用法
- linux popen 用法
- linux C编程--popen函数详解
- linux C编程--popen函数详解
- linux中popen() 函数与system () 详解
- popen() 函数用法
- popen函数详解
- popen函数详解
- subprocess.Popen()详解
- linux popen函数
- Linux c的popen()
- Linux popen()函数使用
- linux popen函数
- linux popen函数
- linux popen函数
- 管道 linux popen(一)
- SQL从入门到精通
- 在U盘上运行Win8!使用 Windows To Go 制作便携的 Win8 U盘/移动硬盘教程 (视频) - 好软之家
- socket常见问题----《四》
- c与c++ static函数的区别
- 1293. 3n+1数链问题
- linux popen用法详解
- 解决开机时svchost.exe的CPU占用率过高导致系统异常缓慢 - 好软之家
- [算法]1~4 组成无重复数字的三位数
- 三星GT-i9001详细刷机教程
- 深入了解Oracle ASM(一):基础概念
- Windows上64位编程
- linux下用gdb调试c程序
- JS 分页
- 1147. 谁拿了最多奖学金