Fork () and "\ n"

I just made a simple demo program Cto see how it works fork()and came across something that I do not understand. In this example:

void fork2()
{
    printf("A");
    fork();
    printf("B");
}

Conclusion ABAB, but in this example:

void fork2()
{
    printf("A\n");
    fork();
    printf("B\n");
}

Output ABB(single lines, of course). The second one makes sense, because if I understand correctly fork(), he gives birth to a new child, which begins immediately after where the event occurred fork()(therefore, printf("B\n");in this case). I don’t understand why the output is different from when I include a new line character.

+3
source share
2 answers

printf() . , \n -less A , forks.

( PID -), , A.

B . , , AB, .

, \n, printf(), , .

+9

, fork() . fork() - , .

fork(), () , , fork(). fork() PID ; 0. , , , .

. , 2 , . , , , .

, printf() fprintf(), ( ).

+1

Source: https://habr.com/ru/post/1673336/


All Articles