2014-12-04 1 views
1

높은 수준의 권한으로 파일을 작성하기 위해 부모 프로세스가 authopen 인 하위 포크에서 대기하려고합니다. 부모 프로세스의 자식 프로세스가 종료 될 때 부모 프로세스에있는 wait/waitpid이 무기한 정지됩니다. 프로그램이 종료 될 때까지 authopen이 파일을 릴리스하지 않기 때문입니다.C - 상위 프로세스가 자동 실행중인 분기 된 자식 프로세스에서 무기한 대기합니다.

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]) 후'는'' –

+1

하지만 더 중요한 것은이, 부모가 [1], 아이가 아마 때문에 핍을 종료해야합니다 가까운 ([0] PIP)한다 파이프로부터의 판독을 차단한다. –

+0

예, 'authopen'은 표준 입력에서 EOF를받을 때까지 종료되지 않습니다. –

답변

1

파이프 작성이 끝나면 파이프를 닫아야합니다. 그렇지 않으면 판독기가 더 많은 데이터를 기다립니다. 예 :

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