pid = fork();
if (pid == 0) val += 3;
if (val == 5) val++;
printf(“val=%d\n”, val);
Case 1: After fork()
, parent gets scheduled before the child , and complete's printf()
call successfully
val = 6; //printed by parent
val = 8; //printed by child
Case 2: After fork()
, parent gets scheduled before the child , and complete's printf() call successfully
val = 8; //printed by child
val = 6; //printed by parent
-- Problem with printf()
and fork()
--
#include<stdio.h>
#include <sys/types.h>
int main()
{
printf("Before forking");
pid_t pid = fork();
if (pid == 0)
printf("child printing");
else
printf("parent printing");
}
The output is
term# ./a.out
Before forkingparent printingBefore forkingchild printing
The problem above is clear that , the statement "Before forking" , is printed twice , where it should have printed only once.
The solution is
Use '\n'
, to buffer each line after every printf()
call.
As rightly advised here call fflush(0)
, to empty all I/O buffers before forking.