c - 在 C 中使用 execvpe 执行命令

标签 c linux segmentation-fault pipe

对于一个项目,我应该将命令的输出通过管道传输到我的 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有效或我该如何解决这个问题?

最佳答案

假设您的系统有 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()仅在失败时返回,因此没有必要测试其返回状态。它不在错误消息中包含系统错误消息,但您可以修改代码以包含 <errno.h><string.h>并使用 errnostrerror()也报告该信息。

关于c - 在 C 中使用 execvpe 执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313542/

相关文章:

c++ - 迭代求和中的段错误

linux - 如何在子进程中正确接收来自键盘的标准输入?

c++ - 音频编程数据类型

C - 当标准输入的缓冲区中已有数据时,在标准输入上选择()

php - Wordpress - 具有相同数据库表的多个博客页面

c++ - 我怎样才能用智能指针做到这一点?

c - 如何将 fscanf 中的 char 用作 int

c++ - 使用gcc在C中链接C++静态库

mysql - 读取用户输入并将其发送到 MySQL

c - 使用指向结构的双指针和结构指针重新分配动态二维数组