我正在使用 fork-exec 模式编写一些代码,子进程旨在打开 /tmp 目录中的文件(追加创建模式)以将其输出写入。(该文件事先不存在,而是在打开时创建,或者至少应该是......)但是,我发现孩子在执行后无法打开任何文件。它可以在fork之后和exec之前打开/创建一个文件并写入它,但是在exec之后我发现该文件没有被创建。此外,如果我在命令行上运行我正在执行的程序(使用相同的参数),它会创建文件并写入它就好了。只有当它从 exec 开始时,它似乎才有这个问题。我真的不知道如何开始考虑这个问题......如果有人对在哪里寻找线索有建议,我真的很感激!
这是一个粗略的示例 - 请注意,这不是运行的实际代码:) 孩子:
#define MSG "Opened file: "
int main (usual stuff) {
    const char* szTemp = "/tmp/helloworld";
    FILE* temp = fopen(szTemp, "a");
    fwrite(MSG, sizeof(char), strlen(MSG), temp);
    fwrite(szTemp, sizeof(char), strlen(szTemp), temp);
    fwrite("\n", sizeof(char), 1, temp);
    fclose(temp);
    // at this point, I see the file with the normal content when Child is run
    // from the command line, but the file is not created if Child is created
    // by a call to exec
}
家长:
int main(usual stuff) {
    pid_t pid = fork();
    if (0 == pid) {
        // fopen/fwrite works fine if I do it here!
        exec(child-process);
    }
    // parent continues...
}