Chinaunix首页 | 论坛 | 博客
  • 博客访问: 63328
  • 博文数量: 28
  • 博客积分: 230
  • 博客等级: 二等列兵
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-01 09:44
文章分类

全部博文(28)

文章存档

2016年(1)

2015年(2)

2014年(11)

2013年(7)

2012年(7)

我的朋友

分类: LINUX

2013-03-28 09:12:57



    linux下可以使用popen完成这个功能. 
     linux中一般通过system()系统调用执行相应的shell或app程序,但其返回的结果只有'0'或'-1',为了能够获取被执行程序的stdout输出,我们可以考虑使用popen();

#include
       FILE *popen(const char *command, const char *type);
       int pclose(FILE *stream);

        popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。
        type 参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。
       popen使用的shell是 /bin/sh 
示例如下:
  

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>

  6. char* cmd_system(const char* command);
  7. int main()
  8. {
  9.     char* result = cmd_system("ls -lh ");
  10.         printf("The result:%s\n",result);
  11.     return 0;
  12. }

  13. char* cmd_system(const char* command)
  14. {
  15.     char* result = "";
  16.     FILE *fpRead;
  17.     fpRead = popen(command, "r");
  18.     unsigned char buf[1024*20];
  19.     int ibuflen = 0;
  20.     memset(buf,'\0',sizeof(buf));
  21.     int tr = 0;
  22.     while((tr = fgetc(fpRead))!=EOF)
  23.     {
  24.         buf[ibuflen++] = (unsigned char)tr;
  25.     }
  26.     buf[ibuflen++] = '\0';
  27.     result = buf;
  28.     if(fpRead!=NULL)
  29.         pclose(fpRead);
  30.     return result;
  31. }


参考:http://www.cnblogs.com/loulijun/archive/2012/05/08/2490738.html 
阅读(2585) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~