【发布时间】:2016-04-06 08:52:29
【问题描述】:
我正在尝试从 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);
可惜在调用部分,当我printftmp时,只包含命令输出的最后一行。
知道我做错了什么吗?我怎样才能得到所有行 int *result 并因此进入tmp?
【问题讨论】: