I have written a program where I have created a child process. Both the parent process and child process do calculation in two parts- parent_part1 , parent_part2 and child_part1, child_part2.
My aim is to run the (parent_part1,child_part1,parent_part2 ,child_part2) sequence for let us say 5 times. For this purpose I have used while(var_child++<10) and while(var_par++<10) and successfully achieved it.
Now, I will define ONE SUCCESSFUL calculation is execution of (parent_part1,child_part1,parent_part2 ,child_part2) sequence for 5 times and display the final correct value.
I want to find such 100 SUCCESSFUL calculation and for the same purpose I have used OUTER loop (i.e., while(t1++<100) ), but I am not getting the SUCCESSFUL calculation for 100 times , sometimes I got 40 SUCCESSFUL result, and hanged after parent_part1 or parent_part2 or child_part1 or child_part2 etc. and some other times I got 20 or 95 SUCCESSFUL result, and hanged after parent_part1 or parent_part2 or child_part1 or child_part2 etc.
What is the reason and how to overcome this ? Thank you in advance . The program is as below.
#include<stdio.h>
#include<signal.h>
int flagp=0,flagc=0,var_child=0,var_par=0;
void write_child()
{
if(flagc==0)
{
/* do some computation here*/
printf("Child_part1 \n");
flagc=1;
}
else
{
/* do some computation here*/
flagc=0;
printf("Child_part2 \n");
}
}
void write_parent()
{
if(flagp==0)
{
/* do some computation here*/
printf("Parent_part1 \n");
flagp=1;
}
else
{
/* do some computation here*/
printf("Parent_part2 \n");
flagp=0;
}
}
int main(int ac, char **av)
{
printf("Starting...\n");
int t1=0;
pid_t childpid = fork();
printf("childpid=%d,getppid()=%d \n",childpid,getppid());
while(t1++<100)
{
var_child=0;
var_par=0;
if ( childpid == 0 )
{
// child process
printf("\n\nt1=%d ",t1);
while(var_child++<10)
{
kill(getppid(), SIGCONT); //sending singal to parent
signal(SIGCONT, write_child);
pause();
}
}
else
{
//parent process
printf("\n\nt1=%d ",t1);
while(var_par++<10)
{
kill(childpid, SIGCONT); //sending singal to child
signal(SIGCONT, write_parent);
pause();
}
} // end of else
}
return 0;
}