I need to create a certain number of concurrent child processes. I also want each child process to modify a global variable so the main parent process can print it in its last modified version. When I run the program below, the final value for ‘k’ will be 5, so the global variable does not change. If I remove the “exit(0)” part, then the global variable changes but this time the number of child processes created gets bigger.
Using fork(), how would I create an X number of child processes that can modify the 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;
}
As Kevin commented, what you really want is threads.
Doing IPC for this is overkill.
Look at the following link.
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html