James Bryant

【转载】C语言获取Shell返回结果

0
阅读(1040)

  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混合编程。

-- 不登高山,不知天之高也;不临深溪,不知地之厚也。