2014-12-04 64 views
1

我想让我的父进程在运行authopen的子分支上等待写入具有提升特权的文件。父项中的wait/waitpid将无限期挂起以终止子进程。我相信这是因为authopen在程序退出之前不会释放该文件。C父进程无限期地等待分叉的子进程运行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; 
} 
+0

后你'DUP(PIP [0])'你应该'接近(PIP [0])' – 2014-12-04 00:37:21

+1

但更重要的是,父母需要关闭画中画[1],因为孩子可能是阻塞从管道读取。 – 2014-12-04 00:38:39

+0

是的,'authopen'不会退出,直到它的标准输入接收到EOF为止。 – 2014-12-04 00:39:11

回答

1

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

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