Wednesday, May 16, 2012

Synchronizing alternatively two processes in Linux C

TI need two son processes to do this:




  • Son process 1 should printf even numbers between 0 and 100.

  • Son process 2 should printf odd numbers between 0 and 100.



What I should see in terminal after execution is: 0 1 2 4..100



How can I do this?



I tried this program, but it doesn't work, it only gives me the first integer 0:



#include <unistd.h>
#include <stdio.h>
#include <signal.h>

void handler1(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}

void handler2(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}

int main()
{
int i=-1;

if(fork()==0)
{
signal(SIGCONT,handler1);
while(1)
{

printf("%d\n",i+1);
pause();
kill(getpid()+1,SIGCONT);
}
}

if(fork()==0)
{
signal(SIGCONT,handler2);
while(1)
{
pause();

printf("%d\n",i+1);
kill(getpid()-1,SIGCONT);
}
}

}




No comments:

Post a Comment