Linux下C程序获得shell脚本输出

shell脚本输出结果重定向

课设里面,需要查看系统的相关信息。指导书上直接打开文件来获得,但我发现通过terminal中的一些命令更容易获得自己想要的信息,于是就研究如何把终端中输出的结果重定向过来。

使用popen

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

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

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


下面看一个示例,将free -m命令输出情况重定向输出到buf中,方便处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <sys/types.h> 
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main( void )
{
FILE *stream;
char buf[1024];

memset( buf, '\0', sizeof(buf) );
stream = popen( "free -m", "r" );

fread( buf, sizeof(char), sizeof(buf), stream);
printf("%s\n", buf);
pclose( stream );

return 0;
}
0%