读书人

在linux下怎样用C程序截获shell输出

发布时间: 2012-02-29 16:44:11 作者: rapoo

在linux下,怎样用C程序截获shell输出结果
对于一条linux下shell命令,如:“ls -l”,通过systems()或exec()系统调用嵌入到C程序中去执行,同时想在C程序中通过一个字符数组来保存shell命令输出到stderr和stdout信息。在C中怎样才能截获到?
  请高手指点指点~~

[解决办法]
FILE *popen(const char *command, const char *type);

int pclose(FILE *stream);

DESCRIPTION
The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by defi-
nition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is
correspondingly read-only or write-only.
FILE *file;
char buf[128];
file=popen( "ls -l " , "r ");
.......下边自己处理一下就可以了.
fgets(buf,sizeof(buf),file);

[解决办法]
io冲定向

读书人网 >C语言

热点推荐