user1398371
user1398371

Reputation: 11

Synchronizing alternately two processes in Linux C

I need two child processes to do this:

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);
     }
  }

} 

Upvotes: 1

Views: 686

Answers (1)

stanwise
stanwise

Reputation: 2412

Signals are not a good solution for this problem. The first signal gets lost (it is sent by the first child before the second child starts), and you end up locked (because one of the processes is waiting for a signal that it had already missed).

Try using semaphores or message queues instead. They are immune to this problem, because they don't get lost in the system, even when not all processes involved are already started.

Upvotes: 2

Related Questions