码迷,mamicode.com
首页 > 编程语言 > 详细

C语言获取Shell返回结果

时间:2016-07-01 11:42:01      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

  Linux编程时候,如果我们需要调用shell命令或脚本通常使用system方法。如system("ls")

  该方法返回值为0或-1,即成功或失败。而有的时候我们想要获取shell命令执行的结果,该怎么办呢?

  我们可以将shell命令结果重定向到文件中,然后再读取这个文件,如:

    system("ls>result.txt")

    FILE *fp = fopen(result, "r")

  当然我们也可以直接使用管道,如下面示例:

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

char* shellcmd(char* cmd, char* buff, int size)
{
    char temp[256];
    FILE* fp = NULL;
    int offset = 0;
    int len;
    
    fp = popen(cmd, "r");
    if(fp == NULL)
    {
        return NULL;
    }

    while(fgets(temp, sizeof(temp), fp) != NULL)
    {
        len = strlen(temp);
        if(offset + len < size)
        {
            strcpy(buff+offset, temp);
            offset += len;
        }
        else
        {
            buff[offset] = 0;
            break;
        }
    }
    
    if(fp != NULL)
    {
        pclose(fp);
    }

    return buff;
}

int main(void)
{
    char buff[1024];

    memset(buff, 0, sizeof(buff));
    printf("%s", shellcmd("ls", buff, sizeof(buff)));

    return 0;
}

  

  注意:C语言调用shell命令是新建一个进程执行的,执行速度很慢,最好不要C、Shell混合编程。

 

C语言获取Shell返回结果

标签:

原文地址:http://www.cnblogs.com/supernalsnow/p/5632250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!