2016-06-25 3 views
1

에 표시되지 나는 다음과 같은 코드를 가지고 :자녀의 printf와는 부모 프로세스의 콘솔

이 출력 결과
#include <sys/types.h> 
#include <sys/wait.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 
#include <stdlib.h> 

// child process is forked. 
// the child executes "ls -al" 
// the parent process "waits" for the child and collects it 

int main(void) { 

    char *args[3]; 
    pid_t pid; 

    printf("i am a parrent and my pid=%d\n",getpid()); 
    if ((pid = fork()) < 0) 
     fprintf(stderr, "fork error"); 
    else if (pid == 0) { 
     /* child */ 
     printf("i am a child and my pid=%d",getpid()); 
     args[0] = strdup("ls"); 
     args[1] = strdup("-al"); 
     args[2] = NULL; 
     if (execvp(args[0], args) < 0) 
      fprintf(stderr, "exec error"); 
    } 
    printf("my child got pid=%d\n",pid); 
    /* parent */ 
    if (waitpid(pid, NULL, 0) < 0) 
     fprintf(stderr, "waitpid error"); 
    exit(0); 
} 

:

i am a parrent and my pid=11745 
my child got pid=11750 
total 144 
drwxr--r-- 3 student student 4096 Jun 25 21:18 . 
drwxrwxr-x 4 student student 4096 May 24 17:18 .. 

다른 파일 ...

내 질문 is : 왜 어린이의 printf ("i am a child...") 출력이 콘솔에 표시되지 않고 ls의 출력이? 상위 프로세스와 동일한 콘솔에서이를 표시하려면 어떻게해야합니까?

+1

메시지에 캐리지 리턴을 추가하십시오. 'printf ("나는 자식이고 내 pid = % d \ n", getpid());' – wildplasser

+0

이제는 작동하지만 왜 "\ n"이 없지 않았습니까? –

+0

\ r은 캐리지 리턴입니다. \ n은 줄 바꿈입니다. – Shiro

답변

0

먼저 당신은 fork 전에 fflush(stdout);이 필요하거나 다른 당신은 가능성이 모두 당신이 부모와 자녀의 표준 출력 버퍼있어에서 printf("i am a parrent and my pid=%d\n",getpid());의 출력이 될 것입니다. 그러면 exec은 이전 프로세스 이미지와 출력 버퍼를 완전히 낭비하기 때문에 exec 호출 전에 fflush(stdout) 또는 fcloseall()이 필요합니다.

또는 회선 버퍼링으로 전환하거나 해제 할 수 있습니다.

exec 오류를 처리하는 중 오류를 인쇄하는 것 이외에 _exit도 입력해야합니다. 그렇지 않으면 상위 경로가 계속됩니다.

관련 문제