linux poen函数
来源:互联网 发布:java 8实战 mobi 编辑:程序博客网 时间:2024/06/05 06:03
函数原型:
#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文件内写入“Read pipe 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 !
当使用type 参数为 “r" 时,popen 会把执行 command 后的标准输出重定向到管道流。但是,command执行中的标准错误输出,在管道流中得不到。
那么,有没有办法来同时获取到 command 执行后的标准输出和标准错误输出呢?答案是肯定的!
只要在 command 中,将标准错误输出重定向到标准输出即可!
例如:
FILE *stream;
stream = popen(, "cp -f 2>&1", "r");
while(fgets(s, 1024, stream))
{
printf(s);
}
- linux poen函数
- poen 用法
- poen实现 把小写字母换成大写字母
- LINUX函数
- linux函数
- Linux 函数
- linux 函数
- Linux 函数--access函数
- strdup函数 -- linux函数
- umask()函数 -- linux函数
- ftok() Linux Linux函数
- Linux fopen函数 stat函数
- Linux多线程函数pthread_create()函数
- Linux系统函数write()函数
- 嵌入式linux:Linux时间函数
- linux的系统函数
- Linux C 函数介绍
- Linux系统函数
- service(2)
- 怎么下载旧版本的 NDK
- Linux系统安装完Qt后,Qt无法显示菜单栏问题
- SharePoint 2010 master page 控件介绍(2):ribbon (一同事读听着像泪奔)
- 如何在命令行中打印格式化的json和xml数据
- linux poen函数
- 织梦DedeCms V5.5/V5.6/v5.7等安全设置指南2013 最安全攻略
- SQL Server中临时表与表变量的区别
- 黑马程序员_java_基础加强_模拟交通灯管理系统
- 业绩评价
- JNI简介
- sed简明教程
- Hadoop2.2.0多节点分布式安装及测试
- Spring 3.x jar 包详解 与 依赖关系