在 C 中使用 execvpe 执行命令

Ale*_*lex 1 c linux pipe segmentation-fault

对于一个项目,我应该将命令的输出通过管道传输到我的 C 程序(称为执行),然后该程序将执行该命令。

\n\n

例如,运行这个:\n echo ls -lR /usr | ./execute,将获取输出 ( ls -lR /usr) 并将其传递到我的 C 程序中,然后该程序将执行ls -lR /usr

\n\n

根据指示,我应该用来execvpe()实际执行程序,但是我找不到任何有意义的文档,也无法在不出现这些错误的情况下让它工作:

\n\n
execute.c: In function \xe2\x80\x98main\xe2\x80\x99:\nexecute.c:98: warning: implicit declaration of function \xe2\x80\x98getenv\xe2\x80\x99\nexecute.c:98: warning: assignment makes pointer from integer without a cast\nexecute.c:106: warning: implicit declaration of function \xe2\x80\x98execvpe\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的教授说我必须#include <unistd.h>解析<stdio.h>程序的输入(我也这样做了),然后执行以下操作:

\n\n
int main(void) {\n    char *path;\n    path = getenv("PATH");\n    char *envp[] = {path, NULL};\n    // the initialized array below could change normally.\n    // below is just an example\n    char *tests = {"ls", "-lR", NULL};\n    int ret = execvpe("ls", tests, envp);\n    if(ret == -1) { printf("error\\n"); }\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后他表示 execvpe 应该正确找到路径并执行所有内容。但无论如何,我不断收到这些警告。运行程序并忽略警告会立即出现错误。有谁知道如何execvpe工作或如何解决这个问题?

\n

Jon*_*ler 5

假设您的系统具有execvpe()以下功能,此代码应该可以工作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void) {
    char *path = getenv("PATH");
    char  pathenv[strlen(path) + sizeof("PATH=")];
    sprintf(pathenv, "PATH=%s", path);
    char *envp[] = {pathenv, NULL};
    char *tests[] = {"ls", "-lR", NULL};
    execvpe(tests[0], tests, envp);
    fprintf(stderr, "failed to execute \"%s\"\n", tests[0]);
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

更新为PATH=$PATH环境中的格式。

它修复了 上的编译错误tests,用作tests[0]; 的命令名称execvpe()。它报告标准错误的错误;它包括未执行的命令的名称;退出时返回失败状态(非零);它指出,execvpe()仅在失败时才返回,因此无需测试其返回状态。它不包括错误消息中的系统错误消息,但您可以修改代码以包含<errno.h><string.h>并使用errnostrerror()来报告该信息。