2014-04-04 2 views
1
#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 
#include <unistd.h> 

int main(void) 
{ 
    pid_t Checksum_pid = fork(); 

    if (Checksum_pid < 0) 
     printf("Fork Failed\n"); 
    else if (Checksum_pid == 0) 
    { 
    printf("\nInside Child Process before execl");   
    //execl("/bin/sleep", "/bin/sleep", "2", NULL); 
    execl("/bin/ls","ls",(char *)NULL) ; 
     //exit(EXIT_FAILURE); 
    printf("\nInside Child Process after execl\n"); 
    exit(EXIT_FAILURE); 
    } 
    else 
    { 
     int childStatus;   
    printf("\nInside Parent Process"); 
    sleep(5); 
    pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG); 

     if (returnValue > 0) 
     { 
      if (WIFEXITED(childStatus)) 
       printf("\nChild Exit Code: %d\n", WEXITSTATUS(childStatus)); 
      else 
       printf("\nChild Exit Status: 0x%.4X\n", childStatus); 
     } 
     else if (returnValue == 0) 
      printf("\nChild process still running\n"); 
     else 
     { 
      if (errno == ECHILD) 
       printf("\nError ECHILD!!\n"); 
      else if (errno == EINTR) 
       printf("\nError EINTR!!\n"); 
      else 
       printf("\nError EINVAL!!\n"); 
     } 
    printf("\nParent: I am about to finish\n"); 
    } 

    return 0; 
} 

출력 : 마지막으로 내가 0으로 시도인쇄 출력에 표시되지 않습니다

kth4kor-2:~/bosch/Test1$ ./a.out 
Inside Parent Process 

Child process still running 

Parent: I am about to finish 

[email protected]:~/bosch/Test1$ a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ 

: I (5) 부모에 다음 출력을 잠을 제거하면 이제

kth4kor-2:~/bosch/Test1$ ./a.out a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ 
Inside Parent Process Child Exit Code: 0 
Parent: I am about to finish 

WNOHANG 대신에 waitpid에 대한 세 번째 주장은 어린이의 지문과 함께 아래 출력을 주었다.

kth4kor-2:~/bosch/Test1$ ./a.out 
a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ 
Inside Parent Process 
Child Exit Code: 0 
Parent: I am about to finish 

누군가 execl을 실행하고 실행하기 전에 프로세스의 동작을 이해할 수 있습니까?

+2

@Joachim이 언급 한 해결책 이외에'setbuf (stdout, NULL); "을 사용하여 버퍼링을 비활성화하거나'stderr'에서 메시지를 출력 할 수 있습니다. –

+0

printf ("\ n execl 이전의 하위 프로세스 내부 \ n"); 잘 작동하고 있습니다 ... – kapilddit

답변

6

printf (~ stdout)을 통한 출력은 일반적으로 라인 버퍼입니다. 즉, 출력 버퍼가 줄 바꿈에 플러시되는 것을 의미합니다. 인쇄하려는 문자열 뒤에 개행 문자가 없으므로 출력 버퍼가 비워지지 않습니다.

문자열에 마지막으로 새 줄을 추가하거나 수동으로 버퍼를 플러시합니다 (fflush).

+0

감사합니다. execl이 보이기 전에 printf를 의미합니다 !! 어떤 execl이 자식 프로세스와 관련이 있을까요? 나는 execl이 프로세스의 이미지를 만들 것이라고 읽었습니다. 성공하면 execl의 리턴 코드는 무엇입니까? – kapilddit

+1

@kapilddit'execl' (및 패밀리)가 성공하면 * 돌아 오지 않습니다 *. 그것은 실패로 돌아올 것입니다. 현재 프로세스의 이미지 (대략적으로 프로그램)를 호출에 의해로드 된 이미지로 대체 *하는 것입니다. –

+0

sleep (5)을 사용하지 않으면 하위 프로세스는 어떻게됩니까? 부모 프로세스에서. 그러면 자식 프로세스가 고아가됩니까? msg를 "자식 프로세스가 계속 실행 중"입니다. 어떻게 waitpid에서 WNOHANG와 부모 프로세스에서 sleep (5)을 사용하고 싶지 않다면 그것을 해결할 수 있을까요? – kapilddit

관련 문제