C语言获取Shell返回结果

  Linux编程时候,若是咱们须要调用shell命令或脚本一般使用system方法。如system("ls")shell

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

  咱们能够将shell命令结果重定向到文件中,而后再读取这个文件,如:spa

    system("ls>result.txt")code

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

  固然咱们也能够直接使用管道,以下面示例:进程

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

相关文章
相关标签/搜索