Ale*_*lex 1 c linux pipe segmentation-fault
对于一个项目,我应该将命令的输出通过管道传输到我的 C 程序(称为执行),然后该程序将执行该命令。
\n\n例如,运行这个:\n echo ls -lR /usr | ./execute,将获取输出 ( ls -lR /usr) 并将其传递到我的 C 程序中,然后该程序将执行ls -lR /usr。
根据指示,我应该用来execvpe()实际执行程序,但是我找不到任何有意义的文档,也无法在不出现这些错误的情况下让它工作:
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\nRun Code Online (Sandbox Code Playgroud)\n\n我的教授说我必须#include <unistd.h>解析<stdio.h>程序的输入(我也这样做了),然后执行以下操作:
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}\nRun Code Online (Sandbox Code Playgroud)\n\n然后他表示 execvpe 应该正确找到路径并执行所有内容。但无论如何,我不断收到这些警告。运行程序并忽略警告会立即出现错误。有谁知道如何execvpe工作或如何解决这个问题?
假设您的系统具有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>并使用errno和strerror()来报告该信息。
| 归档时间: |
|
| 查看次数: |
14018 次 |
| 最近记录: |