LINUX中编写函数实现system功能

在Linux编程中,经常要调用一些系统命令或SHELL脚本来帮助我们完成一些操作,大部分情况下system函数可以胜任,但有时在操作完成之后,我们还要获取它的输出,这时system函数就无能为力了。为此我编写了一个函数,可以先让系统执行一条命令,然后利用管道技术获取它的输出。

上代码:
  1. #include <sys/types.h>     
  2. #include <unistd.h>     
  3. #include <stdlib.h>     
  4. #include <stdio.h>     
  5. #include <string.h>    
  6.   
  7. #define MAXLINE 1024    
  8.   
  9. //调用系统命令,并获取输出(相当于使用system)    
  10. //input: 要调用的系统命令    
  11. //output: 调用命令后系统的输出    
  12. //maxlen: 输出字符串的最大长度    
  13. int mysystem(char *input, char *output, int maxlen)    
  14. {    
  15.     if( NULL==input || NULL==output )    
  16.         return -1;    
  17.     int reslen;    
  18.     FILE *stream;    
  19.     memset(output, 0, maxlen);    
  20.     //创建管道,并将input里的内容写入管道    
  21.     stream = popen(input, "r");    
  22.     //从管理中读出数据,并写入output数组    
  23.     reslen = fread(output, sizeof(char), maxlen, stream);    
  24.     pclose(stream);  
  25.     return reslen;    
  26. }    
  27.   
  28. int main(int argc, char **argv)    
  29. {    
  30.     if( argc != 2 )  
  31.     {  
  32.         fprintf(stderr, "Using: ./mysystem <cmd>\n");  
  33.         exit(1);  
  34.     }  
  35.     char output[MAXLINE];    
  36.     mysystem(argv[1], output, MAXLINE);    
  37.     printf("The result of '%s' is: \n%s", argv[1], output);    
  38.     return 0;    
  39. }    

运行示例:
qch@ubuntu:~/code$ gcc temp.c -o temp
qch@ubuntu:~/code$ ./temp pwd
The result of 'pwd' is: 
/home/qch/code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值