i am trying to synchronize between father process and son process
created by fork() command, to print simultaneously.
my program is written in c under bash shell.
the compile goes ok but when i try to run nothing happens and the program doesnot end.
my code is:
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
main() {
sem_t s1;
sem_t s2;
int value1 , value2;
sem_init(&s1, 0, 1);
sem_init(&s2,0,1);
sem_wait(&s2);
int pid = fork();
if (pid != 0)
{
int i;
for (i=0 ; i<=10 ; i++)
{
sem_getvalue (&s1,&value1);
while (value1 != 1)
sem_getvalue (&s1,&value1);
sem_wait(&s1);
if (i%2 != 0)
printf("%d\n",i);
sem_post(&s2);
}
}
if (pid == 0)
{
int j;
for (j=0 ; j<=10 ; j++)
{
sem_getvalue (&s2,&value2);
while (value2 != 1)
sem_getvalue (&s2,&value2);
sem_wait(&s2);
if (j%2 == 0)
printf("%d\n",j);
sem_post(&s1);
}
exit(0);
}
return 0;
}
is there any other way to synchronize father and son process ?