C系统调用失败

C system calls fails

我正在尝试编写一个代码来操作标准输入和输出并将它们重定向到文件,然后使用 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;
}

我的输入文件只包含 -> 4

我尝试了两个主要的东西:

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

您传递给 execvp() 的参数数组没有 NULL 终止。

根据 the POSIX exec() documentation:

...

The argument argv is an array of character pointers to null-terminated strings. The application shall ensure that the last member of this array is a null pointer. These strings shall constitute the argument list available to the new process image. The value in argv[0] should point to a filename string that is associated with the process being started by one of the exec functions.

...

您的代码应该是

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);
}