#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_PID 3
#define BEGIN 1

int fd[2];
int p_pid[MAX_PID];
// 0 - p1,  1 - p2,  2 - parent  


void SigPlus(int s)
{
 int cnt, res;
 signal(SIGUSR1, SigPlus);

   read(fd[0], &cnt, sizeof(int));
     cnt++;
   write(fd[1], &cnt, sizeof(int));

    if (getpid() == p_pid[0])
     res = 2;
    if (getpid() == p_pid[1])
     res = 0;
    if (getpid() == p_pid[2])
     res = 1;

  //  printf(" ¹ = %d,  pid = %d,  value = %d \n", res, p_pid[res], cnt);
  printf(" pid = %d,  value = %d \n", p_pid[res], cnt);
  kill(p_pid[res], SIGUSR1);
}




void SigInt(int s)
{
printf("\n");
printf("Killing 0, pid = %d \n", p_pid[0]);   kill(p_pid[0], SIGINT);
printf("Killing 1, pid = %d \n", p_pid[1]);   kill(p_pid[1], SIGINT);
}




// ------------------------- MAIN ---------------------------
int main(int argc, char **argv)
{

int status;
int cnt;


 for (cnt = 0; cnt < MAX_PID; cnt++)
  p_pid[cnt] = -1;

 cnt = BEGIN;


 signal (SIGUSR1, SigPlus);
 p_pid[2] = getpid();

 pipe(fd);


// ------------------ FIRST PROCESS -----------------
   if ((p_pid[0] = fork()) == 0 )
   {
    p_pid[0] = getpid();

     for(;;) sleep(9999);
   return 0;
   }

// ------------------ SECOND PROCESS -----------------
   if ((p_pid[1] = fork()) == 0)
   {
     p_pid[1] = getpid();

      // Getting start!
        if (cnt == BEGIN)
         {
          write(fd[1], &cnt, sizeof(int));
           kill(p_pid[0], SIGUSR1);
         }

     for(;;) sleep(9999);
   return 0;
   }


// ------------------ PARENT PROCESS -----------------

     signal (SIGINT, SigInt);

     wait(&status);

    printf("Killing 2, Parent killed.\n");
   close(fd[1]); close(fd[0]);

return 0;
}




