【问题标题】:Executing a command with execvpe in C在 C 中使用 execvpe 执行命令
【发布时间】:2015-02-04 04:32:02
【问题描述】:

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

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

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

execute.c: In function ‘main’:
execute.c:98: warning: implicit declaration of function ‘getenv’
execute.c:98: warning: assignment makes pointer from integer without a cast
execute.c:106: warning: implicit declaration of function ‘execvpe’

我的教授说我必须 #include <unistd.h> 和 <stdio.h> 我做了,解析输入到我的程序(我做了),然后这样做:

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

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

【问题讨论】:

  • 如果你查看手册页,你会发现你的参数类型是错误的(例如,第二个参数是char* const [ ],你有char *)。同样tests 不是char *,它是char* [ ]。手册页还准确地告诉您使用什么 #include。
  • 并非每个系统都提供execvpe() — 例如,Mac OS X 不提供。
  • @JonathanLeffler 我在有它的 linux 服务器上使用 ssh,我会更多地查看手册页,并听取 Apprentice 对 char const 的建议。

标签: c linux segmentation-fault pipe


【解决方案1】:

假设你的系统有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;
}

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

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

【讨论】:

  • 这行得通..ish。不幸的是,测试用例echo which ls | ./execute 会导致which: no ls in ((null))。我想这与 envp 指针有关,我被告知将路径设置为“PATH =”,然后将 getenv(“PATH”) 附加到 strcat。不过,这给了我一个段错误。关于我如何基本上得到字符串的任何想法:“PATH=getenv("PATH")" 没有段错误?
  • @Alex: 嗯,是的……代码应该在环境中设置了PATH=$PATH,现在可以了。不这样做不应该影响答案中代码的操作; execvpe() 使用调用程序的环境,而不是envp 中设置的环境,至少是AFAIK。您必须测试一个不同的程序,该程序实际上读取其标准输入以获取命令,然后将其拆分并尝试执行命令和参数。通常,我会使用snprintf(),但我只是分配了恰到好处的空间量(因为sizeof("PATH=") 计算了尾随的空值)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
相关资源
最近更新 更多