您的位置:首页 > 运维架构 > Shell

获取shell执行结果,不创建实际文件

2011-09-06 13:51 501 查看
popen使用FIFO管道执行外部程序。

#include <stdio.h>

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则用于使用结束后关闭这个指针。

例子:

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main( void )
{
FILE   *fp;
char   buf[1024];
bzero(buf, sizeof(buf));
fp = popen( "ls -l", "r" );
fread( buf, sizeof(char), sizeof(buf),  stream);
pclose( fp );
printf("result is\n==%s==\n", buf);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: