/* SCHEDULER with SEMAPHORES */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

#define NPROC 2

typedef int *semaphore;
semaphore clock, psem[2];
int deadline[NPROC];
int interval[NPROC];
int time = 0;
int sem_array[20];
int p_sem_array = 0;

semaphore make_sem ()
{
  int *sem;

  sem = &sem_array[p_sem_array];
  p_sem_array++;
  p_sem_array++;
  pipe (sem);
  return sem;
}

void WAIT (semaphore s)
{
  int junk;

  if (read (s[0], &junk, 1) <= 0)
    {
      fprintf (stderr, "ERROR: WAIT\n");
      exit (1);
    }
}

void SIGNAL (semaphore s)
{

  if (write (s[1], "s", 1) <= 0)
    {
      fprintf (stderr, "ERROR: signal\n");
      exit (1);
    }
}

void proc0 ()
{
  int i;

  while (1)
    {
      WAIT (psem[0]);
      i = getpid ();
      printf ("I'm the process %d", i);
      system ("date");
    }
}

void proc1 ()
{
  int i;

  while (1)
    {
      WAIT (psem[1]);
      i = getpid ();
      printf ("I'm the process %d", i);
      system ("date");
    }
}

void catcher ()
{
  printf ("tick\n");
  SIGNAL (clock);
  signal (SIGALRM, catcher);
}

void the_alarm ()
{
  signal (SIGALRM, catcher);
  while (1)
    {
      alarm (1);
      pause ();
    }
}


int main ()
{
  int i;


  clock = make_sem ();
  psem[0] = make_sem ();
  psem[1] = make_sem ();

  /* Initialize the scheduler */
  interval[0] = 5;
  interval[1] = 7;
  deadline[0] = 5;
  deadline[1] = 7;

  if ((i = fork ()) == 0)
    proc0 ();
  if (fork () == 0)
    proc1 ();
  if (fork () == 0)
    the_alarm();

  /* Control of the scheduling */

  while (1)
    {
      WAIT (clock);
      time++;
      for (i = 0; i < NPROC; i++)
	{

	  if (deadline[i] <= time)
	    {
	      deadline[i] = time + interval[i];
	      printf ("WAKE UP the process %d at time %d\n", i, time);
	      SIGNAL (psem[i]);
	    }
	}


    }
}
