【问题标题】:C system calls failsC 系统调用失败
【发布时间】:2019-11-26 18:27:27
【问题描述】:

我正在尝试编写一个操作标准输入和输出并将它们重定向到文件的代码,然后使用 execvp(也尝试过其他 exec)运行一个仅使用 printf 和 scanf 的程序,但 execvp 失败..

相关代码:

    int pid2 = fork();
    if (pid2 == 0) {
        int fdInput = open("myinputfile", O_RDONLY);
        close(0);
        dup(fdInput);
        int fdOutput = open("results.txt", O_WRONLY | O_CREAT | O_TRUNC);
        close(1);
        dup(fdOutput);
        char* tmp[]={"...somepath/prog"};
        execvp("...somepath/prog", tmp);
    }

我的前卫:

int main(){
    int x;
    scanf("%d",&x);
    printf("Hello World! %d",x);
    return 0;
}

myinputfile 仅包含 -> 4

我主要尝试了两件事:

  • 从 prog 复制代码并将其硬编码到我的代码中,而不是调用 execvp,这工作正常,我可以在 results.txt 中看到“Hello world!4”
  • 在终端中手动运行“mypath”,这似乎也可以工作(使用标准 I/O)。

我不明白为什么它不起作用,我尝试了我能想到的一切..

【问题讨论】:

  • char* tmp[]={"...somepath/prog"}; 这是您的实际代码吗?我假设不是。您能否显示您已编译和运行的实际代码。 “但是 execvp 失败了”。这到底是什么意思? execvp 是否返回错误。如果是这样,errno 是什么?
  • 既然你问的是系统调用,你的目标是什么系统?

标签: c io system-calls execvp


【解决方案1】:

您传递给execvp() 的参数数组不是NULL-终止的。

the POSIX exec() documentation:

...

参数argv 是一个指向以空字符结尾的字符串的字符指针数组。 应用程序应确保此数组的最后一个成员是空指针。 这些字符串应构成可用于新进程映像的参数列表。 argv[0] 中的值应该指向一个文件名字符串,该字符串与正在由 exec 函数之一启动的进程相关联。

...

你的代码应该是

int pid2 = fork();
if (pid2 == 0) {
    int fdInput = open("myinputfile", O_RDONLY);
    close(0);
    dup(fdInput);
    int fdOutput = open("results.txt", O_WRONLY | O_CREAT | O_TRUNC);
    close(1);
    dup(fdOutput);

    // note the NULL terminator
    char* tmp[]={"...somepath/prog", NULL };
    execvp("...somepath/prog", tmp);
}

【讨论】:

    猜你喜欢
    • 2015-02-21
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2023-03-31
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多