linux获取程序的输出,linux C程序中获取shell脚本输出(如获取system命令输出)

4. 使用popen 在学习unix编程的过程中,发现系统还提供了一个popen函数,可以非常简单的处理调用shell,其函数原型如下: FILE *popen(const char *command, const char *type); 该函数的作用是创建一个管道,fork一个进程,然后执行shell,而shell的输出可

4. 使用popen

在学习unix编程的过程中,发现系统还提供了一个popen函数,可以非常简单的处理调用shell,其函数原型如下:

FILE *popen(const char *command, const char *type);

该函数的作用是创建一个管道,fork一个进程,然后执行shell,而shell的输出可以采用读取文件的方式获得。采用这种方法,既避免了创建临时文件,又不受输出字符数的限制,推荐使用。

popen使用FIFO管道执行外部程序。

#include

FILE *popen(const char *command, const char *type);

int pclose(FILE *stream);

popen 通过type是r还是w确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的stdout,popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。

下面看一个例子:

/*******************************************************************************************

** Name:popen.c

**      This program is used to show the usage of popen() .

** Author:zieckey,(zieckey@yahoo.com.cn)

** Date:2007/9/30 11:47

** All rights reserved!

*******************************************************************************************/

#include

#include

#include

#include

#include

int main( void )

{

FILE   *stream;

FILE   *wstream;

char   buf[1024];

memset( buf, '/0', sizeof(buf) );//初始化buf,以免后面写如乱码到文件中

stream = popen( "ls -l", "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream

wstream = fopen( "test_popen.txt", "w+"); //新建一个可写的文件

fread( buf, sizeof(char), sizeof(buf), stream); //将刚刚FILE* stream的数据流读取到buf中

fwrite( buf, 1, sizeof(buf), wstream );//将buf中的数据写到FILE    *wstream对应的流中,也是写到文件中

pclose( stream );

fclose( wstream );

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值