#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h> /* incluim les llibreries necessaries */
#include <fcntl.h>
#include <sys/wait.h>
#include <math.h>
int main(int argc, char *argv[])
{
pid_t pid1, pid2;
int status1, status2, nbytes,nbytes2,max=1;
int i=0;
int p1[2], p2[2], p3[2], p4[2];
int buffer1, buffer2;
int readbuffer1, readbuffer2,readbuffer3,readbuffer4;
void manejador(int sig)
{
close(p3[0]);
printf("Excepción capturadan");
printf("Enviando al padre la señal SIGUSR1 n");
int sig_num1=5;
write(p3[1], &sig_num1,sizeof(int));
}
void manejador2(int sig)
{
close(p4[0]);
printf("Excepción capturadan");
printf("Enviando al padre la señal SIGUSR2 n");
int sig_num2=6;
write(p4[1], &sig_num2,sizeof(int));
}
/*void RutinaTratSIGUSR1(int sig)
{
printf("Enviando SIGUSR1n");
}
void RutinaTratAlarm(int sig)
{
printf("Esperando 3 segundos n");
sleep(3);
}*/
if(pipe(p1) < 0)
{
perror( "Errorn");
}
if(pipe(p2) < 0)
{
perror( "Errorn");
}
if(pipe(p3) < 0)
{
perror( "Errorn");
}
if(pipe(p4) < 0)
{
perror( "Errorn");
}
printf("Soy el padre %dn", getpid());
pid1=fork();
if ( pid1<0)
{
perror("Se ha producido un error n");
}
if ( pid1 == 0 )
{ /* hijo */
close(p1[1]);
//0 = read
nbytes = read(p1[0], &readbuffer1, sizeof(readbuffer1));
printf("Numero recibido1: %d, n", readbuffer1);
while (readbuffer1>i)
{
printf("Soy el primer hijo %d, n", getpid());
printf(" Soy el padre %d,n",getppid());
i++;
//signal(SIGALRM, RutinaTratAlarm);
}
signal(SIGUSR1,manejador);
kill(getppid(),SIGUSR1);
}
else
{ /* padre */
pid2=fork();
if(pid2<0)
{
perror("Se ha producido un error n");
}
if ( pid2 == 0 )
{ /* segundo hijo */
close(p2[1]);
//0 = read
nbytes2 = read(p2[0], &readbuffer2, sizeof(readbuffer2));
printf("Numero recibido2: %d, n", readbuffer2);
while (readbuffer2>i)
{
printf("Soy el segundo hijo %d,n", getpid());
printf(" Soy el padre %d,n",getppid());
sleep(1);
i++;
}
signal(SIGUSR2,manejador);
kill(getppid(),SIGUSR2);
}
else
{ /* padre */
buffer1=5;
buffer2=3;
close(p1[0]);
close(p2[0]);
close(p3[1]);
close(p4[1]);
write(p1[1], &buffer1, sizeof(buffer1)); //Pipe al 1r hijo
write(p2[1], &buffer2, sizeof(buffer2)); //Pipe al 2o hijo
if(read(p3[0], &readbuffer3, sizeof(int)))
//Leer sigusr1
{
pause();
printf("SIGUSR1 recibido %d,n", readbuffer3);
write(p1[1], &buffer1, sizeof(int));
}
if(read(p4[0], &readbuffer4, sizeof(int))) //Leer sigusr2
{
printf("SIGUSR2 recibido %d,n", readbuffer3);
write(p2[1], &buffer1, sizeof(int));
}
/* Esperamos al primer hijo */
waitpid(pid1, &status1, 0);
/* Esperamos al segundo hijo */
waitpid(pid2, &status2, 0);
printf("Soy el padre %dn", getpid());
}
}
return 0;
}