I need to create a certain number of parallel child processes. I also want every child process to change the global variable, so the main parent process can print it in the latest modified version. When I run the program below, the final value for "k" will be 5, so the global variable will not change. If I delete the "exit (0)" part, the global variable will change, but this time the number of child processes created will become larger.
Using fork (), how do I create an X number of child processes that can modify data (global variables, local variables, etc.) in the main parent process?
int k = 5; // global variable int main(){ int i=0; int status; for(i = 0; i<5; i++){ if(fork() == 0){ printf("child %d %d\n", i, ++k); sleep(5); printf("done %d\n",i); exit(0); } } return 0; }
source share