首页 文章

C - 父进程无限期地等待运行authopen的分叉子进程

提问于
浏览
1

我试图让我的父进程等待运行 authopen 的子fork,以编写具有提升权限的文件 . 父级中的 wait/waitpid 无限期挂起以使子进程终止 . 我相信这是因为 authopen 在程序退出之前不会释放文件 .

authopen 写入的文件在程序的生命周期内被锁定,因此无法读取该文件,无法使用其他 authopen 进程写入该文件,并打开该文件 . 在程序退出之前,vim不显示文件的内容 .

首先,我在这里继续 . 当 execl 完成时,它不应该还释放所有资源吗?

其次,我想要一些解决方案 .

下面是一个演示该问题的程序 .

我的平台是OSX .

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

int main(int argc, const char * argv[]) {

    int pip[2];

    if (pipe(pip) != 0) exit(1);    //error creating pipe

    pid_t processId;
    processId = fork();

    if (processId == -1) exit(1);    //pipe error

    if (processId == 0) {   //child process

        //close 'write end' of pipe
        close(pip[1]);

        //close stdin and duplicate the 'read end' of pipe to stdin
        close(0);
        dup(pip[0]);

        //run authopen
        const char * authopenPath = "/usr/libexec/authopen";

        execl(authopenPath, authopenPath, "-c","-w","/usr/local/authopenTest.txt",NULL);

        _exit(1);    //exec* does not return in case of success.
    }
    else {      //parent process

        //close 'read end' of pipe
        close(pip[0]);

        //write to 'write end' of pipe
        char * cstr = "write this to file...";
        write(pip[1], cstr, (strlen(cstr)));

        int status;
        //waitpid(0, &status, WNOHANG);     //this is ok, but doesn't block on child completing
        int p_id = wait(&status);           //PROBLEM: this hangs indefinitely. Why?
        if(p_id != -1)  {
            printf("Exit status %d\n", status);
        }
    }

    return 0;
}

1 回答

  • 1

    完成写入后,需要关闭管道 . 否则,读者继续等待更多数据 . 例如:

    write(pip[1], ...);
    close(pip[1]);
    wait(...);
    

相关问题