c-通过参数引用返回程序的exec输出



我正在尝试从C程序中执行shell命令。

为此,我构建了一个包装函数,它将返回命令本身的退出代码,并使用参数引用变量来返回程序的实际输出。

exec函数包装器如下所示:

int _exec(const void *command, char **result) {
    FILE *fp;
    char path[1035];
    char *eof;
    /* Open the command for reading. */
    fp = popen(command, "r");
    if (fp == NULL) {
        return -1;
    }
    while((eof = fgets(path, sizeof(path), fp)) != NULL);
    /* Fill the parameter reference */
    *result = strdup(path);
    /* close */
    pclose(fp);
    return 0;
}

调用部分如下所示:

int result = 0;
char *tmp;
result =_exec("ls /", &tmp);
printf("%s", tmp);

不幸的是,在调用部分,当I printf tmp时,它只包含命令输出的最后一行。

知道我做错了什么吗?如何使所有行都进入*result,从而进入tmp

使用fread而不是fgetsfgets停止读取每个换行符,但将所有行保存在path缓冲区的第一个位置。此外,您还需要跟踪path中已经存在的字节数,并在每次调用读取函数时将数据保存到path中第一个未使用的位置。

相关内容

最新更新