linux的C获取shell执行返回的结果

linux下通过C执行命令的时候一半都是使用system()方法,但是该方法执行命令返回的值是-1或0,而有时候我们需要得到执行命令后的结果。可以使用管道实现

输出到文件流的函数是popen(),例如

FILE *isr;

isr = popen("ls -l","r"); ls -l命令的输出通过管道读取("r"参数)到isr

下面是演示例子,列出当前可用的loop设备,(必须是root权限才可以执行losetup -f)

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

char* cmd_system(const char* command);
int main()
{
    //char str[20]={"0"};
    char* result = cmd_system("losetup -f");
   
//通过该方法可以将char*转换为char数组 //strcpy(str,result); printf("The result:%s\n",result); return 0; } char* cmd_system(const char* command) { char* result = ""; FILE *fpRead; fpRead = popen(command, "r"); char buf[1024]; memset(buf,'\0',sizeof(buf)); while(fgets(buf,1024-1,fpRead)!=NULL) {
       result
= buf; } if(fpRead!=NULL) pclose(fpRead); return result; }

执行结果:

The result:/dev/loop0

posted on 2012-05-08 21:21  花郎V  阅读(6589)  评论(2编辑  收藏  举报