2017-02-01 1 views
1
#include<stdio.h> 
#include<unistd.h> 
#include<stdlib.h> 

int main(int argc, char ** argv) 
{ 

    int pid; 
    int status; 
    pid = fork(); 

    if (pid < 0) 
    { 
     printf("Cannot create a child process"); 
     exit(1); 
    } 
    else if (pid == 0) 
    { 

     printf("I am the child process. %d \n", getpid()); 
     printf("The child process is done. \n"); 
     fflush(stdout); // it does not write immediately to a disk. 
     exit(0); 
    } 
    else 
    { 

     printf("I am the parent process.%d \n", getpid()); 
     sleep(5); // sleep does not works 
     pid = wait(&status); // want to wait until the child is complited 
     printf("The parent process is done. \n"); 
     fflush(stdout); // it does not write immediately to a disk. 
     exit(1); 
    } 
} 

안녕하세요, 저는 현재 하위 프로세스를 만들려고합니다. 그러나 지금까지는 내가 지금 노력하고있는 것이 좋다. 먼저 자식을 실행하고 출력하고 항상 "부모 프로세스가 완료되었다"라는 메시지를 출력하는 것이다. 현재 C에서 부모 앞에서 자식 실행

I am the parent process.28847 
I am the child process. 28848 
The child process is done. 
The parent process is done. 

이 인쇄되어있다 : 그것은 내 처음
I am the parent process.28847 
The parent process is done. 
I am the child process. 28848 
The child process is done. 

입니다

사용에 내가 잠을 시도하고 (& 상태를) 기다릴 것, 내가 뭐하는 거지 정말 자신이없는 나는 그렇게 분기 자식 프로세스가 끝날 때까지 기다렸다가 부모를 실행하지만 무언가가 작동하지 않습니다.

P. 나쁜 레이아웃, stackoverflow를 사용하여 주먹 시간 미안 해요.

+4

당신은 아마 사용해야합니다 ['대기()'(http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) 또는 ['waitpid()'] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html). –

+3

코드에서 "부모 프로세스가 완료되었습니다"는 (wait()를 사용하기 때문에) 매번 마지막으로 인쇄됩니다. – usr

+0

고마워, 내가 고칠 수 있었다. 나는 뮤텍스와 세마포어를 검사 할 것이고 어떻게 향상시킬 수 있을까? –

답변

1

시도해보십시오. waitpid (-1, NULL, 0); 또는 대기 (NULL); 모든 하위 프로세스가 완료 될 때까지 부모를 차단합니다. 작동하면 절전 모드를 사용할 필요가 없습니다. 코드에

약간의 수정 :

else 
{ 
    int status =0; 
    printf("I am the parent process.%d \n", getpid()); 
    status= waitpid(-1, NULL, 0); // want to wait until the child is complete 
    //Also check if child process terminated properly 
    if(status==0) 
    { 
     printf("Child process terminated properly"); 
    } 
    else 
    { 
     printf("Child process terminated with error"); 
    } 

    printf("The parent process is done. \n"); 

    fflush(stdout); // it does not write immediately to a disk. 

    exit(1); 
} 
관련 문제