printf()는 fork()보다 먼저 호출되지만 printf() 루프는 fork()가 호출될 때마다 표준 출력으로 출력됩니다. '\n'이 이 문제를 해결하는 이유는 무엇입니까? [복사]

printf()는 fork()보다 먼저 호출되지만 printf() 루프는 fork()가 호출될 때마다 표준 출력으로 출력됩니다. '\n'이 이 문제를 해결하는 이유는 무엇입니까? [복사]

플레이하는 동안 fork()다소 이상한 동작을 발견했지만 왜 이런 일이 발생하는지 알 수 없었습니다.

다음 예에서는 각 이전 호출 fork()의 출력이 printf()stdout에 인쇄됩니다. test출력의 값은 printf()실제로 다시 실행되지 않음을 나타냅니다. 그렇지 않으면 test매번 증가됩니다.

\n더 이상한 점(또는 해결 방법의 핵심)은 형식 문자열 끝에 printf()를 추가하면 이 동작이 발생하지 않는다는 것입니다.

왜 이런 일이 일어나는지 아는 사람이 있나요? 아마도 stdout 버퍼와 관련이 있을까요? 나는 이런 일에 익숙하지 않습니다.

아니면 내가 뭔가 끔찍한 잘못을 저질렀나요?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(char* args) {
    pid_t pid;
    int wstatus;
    int test = 0;

    printf("\n[%d] parent start | test = %d ", getpid(), test++);

    // This works fine
    //printf("\n[%d] parent start | test = %d \n", getpid(), test++);

    for(int i = 0; i < 5; i++) {
        if((pid = fork()) == 0) {
            //printf("\n[%d] Child spawned ", getpid());
            exit(0);
        }
        //printf("\n[%d] Printing with fork() commented out works fine", getpid());
    }

    while(wait(&wstatus) > 0);

    printf("\n[%d] parent end\n\n", getpid());
    return 0;
}

산출:

[342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 
[342470] parent end

조금이라도 쓸모가 있다면

$ uname -a
Linux Aspire 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

답변1

printf텍스트 가 작성 되었습니다 .표준 출력.buffer를 호출하여 결국 포크의 각 분기에 기록됩니다 exit.

관련 정보