I am reading a book about Operating Systems and am fairly new to C programming as well (tends to complicate things) but am curious as to why I cannot print the incremented i value when every child is created via the fork(). Does it lie with the child processes or something else? Thanks in advance.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main ()
{
pid_t pid;
int i = 1;
pid = fork();
pid = fork();
pid = fork();
pid = fork();
if (pid == 0) {
printf("got child %d\n", i);
i++;
}
}
You can’t print an incremented value because
iis not being printed after being incremented. The processes spun off byfork()don’t share resources, they each get an independent copy ofi. So you’ll see:over and over. Try this tweak and you’ll see that each of the child processes are getting in to the conditional with the same value: