Don't do the second fork
call as it will create a new child. The first is enough:
for (j = 0; j < 3; ++j)
{
pid_t pid = fork();
if (pid == 0)
{
printf("In child (j = %d)\n", j);
exit(0);
}
else if (pid > 0)
{
printf("In parent (j = %d)\n", j);
}
}
Will print "In child"
three times, with j
equal to 0
, 1
and 2
. The same for the parent printing.
In your real code you should check for errors though.