[GNU/Linux]代码中调用系统命令

#include <stdio.h>

// 返回: -1, 命令行出错; >=0, 实际输出的字节数
int execute(const char* cmdline, char* output, int maxsize)
{
    // 执行命令, 获取输出流
    FILE* fp = popen(cmdline, "r");
    if(!fp) return -1;
    
    // 读取maxsize-1个字节
    int size = 0; // 已读取的字节数
    maxsize -= 1;
    while(!feof(fp))
    {
        int n = fread(output+size, 1, maxsize - size, fp);
        if(n<=0) break;
        size += n;
    }
    
    // 关闭输出
    pclose(fp);
    
    output[size] = 0;
    return size; // 实际读取的字节数	
}

int main()
{
    char buf[1024];
    int n = execute("ifconfig", buf, 1024);
    if(n> 0)
    {
        buf[n] = 0;
        printf("------ output -------\n");
        printf("%s\n", buf);
    }
    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注