在Linux编程中,经常要调用一些系统命令或SHELL脚本来帮助我们完成一些操作,大部分情况下system函数可以胜任,但有时在操作完成之后,我们还要获取它的输出,这时system函数就无能为力了。为此我编写了一个函数,可以先让系统执行一条命令,然后利用管道技术获取它的输出。
上代码:
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define MAXLINE 1024
- //调用系统命令,并获取输出(相当于使用system)
- //input: 要调用的系统命令
- //output: 调用命令后系统的输出
- //maxlen: 输出字符串的最大长度
- int mysystem(char *input, char *output, int maxlen)
- {
- if( NULL==input || NULL==output )
- return -1;
- int reslen;
- FILE *stream;
- memset(output, 0, maxlen);
- //创建管道,并将input里的内容写入管道
- stream = popen(input, "r");
- //从管理中读出数据,并写入output数组
- reslen = fread(output, sizeof(char), maxlen, stream);
- pclose(stream);
- return reslen;
- }
- int main(int argc, char **argv)
- {
- if( argc != 2 )
- {
- fprintf(stderr, "Using: ./mysystem <cmd>\n");
- exit(1);
- }
- char output[MAXLINE];
- mysystem(argv[1], output, MAXLINE);
- printf("The result of '%s' is: \n%s", argv[1], output);
- return 0;
- }
运行示例:
qch@ubuntu:~/code$ gcc temp.c -o temp
qch@ubuntu:~/code$ ./temp pwd
The result of 'pwd' is:
/home/qch/code
qch@ubuntu:~/code$ ./temp pwd
The result of 'pwd' is:
/home/qch/code