/*  
 * ######
 * ## PS_SIG3.c
 * ## ~~~~~~~~~
 * ## 04.02.1995: Creation TL
 * ## 04.02.2008:
  * ######
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/signal.h>
#include <sys/wait.h>

int main()
{
  int   pid, pid1, pid2;   char arg1[ 256 ];   char arg2[ 256 ];
  union wait status;

  /* Creation Fils 1 */
  
  pid1 = fork();
  if ( pid1 == -1 ) {
    printf(" \n PS_SIG3> Creation FILS( 1 ) impossible\n ");
    exit( 1 );
  }

  /* Instructions pour le fils 1 */
  
  if ( pid1 == 0 ) {
    sprintf( arg1, "%d\n", getpid() ); // UNUSED
    execl( "ps_sig1", arg1, 0 );
    /* 
     * Que se passe-t-uil en cas de succes ou d'erreur
     * de l'appel de execl ?
     * Faut-il mettre le PathName de la commande ?
     */
    exit(3);
  }

  /* Creation Fils 2 */
  
  pid2 = fork();
  if ( pid2 == -1 ) {
    printf("\n PS_SIG3> Creation FILS( 2 ) impossible\n" );
    exit( 2 );
  }

  /* Instructions pour le fils 2 */

  if ( pid2 == 0 ) {
    sprintf( arg2, "%d\n", pid1 ); // PID du FRERE
    execl( "ps_sig2", arg2, 0 );
    /* 
     * Que se passe-t-uil en cas de succes ou d'erreur
     * de l'appel de execl ?
     * Faut-il mettre le PathName de la commande ?
     */
    exit( 4 );
  }
  sleep( 10 );

  /* Instructions du Pere */
  
  pid = wait( &status );

  if ( pid == pid1 ) {
    printf( "\nPS_SIG3> FILS( 1 ) arrete par signal %d\n", status );

    /* On demande l'arret de l'autre Fils */
    if ( ( kill( pid2, SIGTERM ) ) == -1) {
      perror( "\n PS_SIG3> Pb. kill (1)" );
    }
  } else if ( pid == pid2 ) {
    printf("\n PS_SIG3> FILS( 2 ) arrete par signal %d\n", status );

    /* On demande l'arret de l'autre Fils */
    if ( ( kill( pid1, SIGTERM ) ) == -1) {
      perror( "\n PS_SIG3> Pb. kill (2)" );
    }
  }

  /* On attend l'arret de l'autre Fils */

  pid = wait( &status );

  if ( pid == pid1 ) {
    printf("\n PS_SIG3> FILS( 1 ) arrete par signal %d\n", status );
  } else if ( pid == pid2 ) {
    printf("\n PS_SIG3> FILS( 2 ) arrete par signal %d\n", status );
  }
  exit( 0 );
}
/* ---  fin  ps_sig3  --- */

