Hello Everyone,
I am trying to write a code where parent process will increment a variable and then child will increment the same variable(its own copy). However, I see that after child process returns to parent by calling exit, it also executes rest of the parents code in its context while using parents copy of the variable. The program is given below.
Code:
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
sem_t mutex;
int main(void)
{
int i, j, fd;
pid_t pid;
int count = 0;
sem_init(&mutex, 1, 1);
/* fork a new process */
if (fork() == 0) {
/* The child will run this section of code */
for (j=0;j<5;j++)
{
sem_wait(&mutex);
printf("Child count %d %d\n", ++count, getpid());
sem_post(&mutex);
}
/* exit the child process */
printf("Child PID(%d): exiting...\n", getpid());
exit;
}
/* The parent will run this section of code */
/* give the child a chance to start running */
sleep(2);
for (i=0;i<5;i++)
{
sem_wait(&mutex);
printf("Parent count %d %d\n", ++count, getpid());
sem_post(&mutex);
}
/* exit the parent process */
printf("Parent PID(%d): exiting...\n", getpid());
return 0;
}
Here is the output:
./a.out
Child count 1 29825
Child count 2 29825
Child count 3 29825
Child count 4 29825
Child count 5 29825
Child PID(29825): exiting...
Parent count 1 29824
Parent count 2 29824
Parent count 3 29824
Parent count 4 29824
Parent count 5 29824
Parent PID(29824): exiting...
Parent count 6 29825
Parent count 7 29825
Parent count 8 29825
Parent count 9 29825
Parent count 10 29825
Parent PID(29825): exiting...
I see that if I use 'return' instead of 'exit' then this problem does not appear. If I use an "if-else" to segregate child and parent code then also this problem does not appear.
Could anyone please help me to understand what is going on here?
Thanks,
With Regards,
Indranil