#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int N = 5;
int _pipe[2];
pid_t children[5];

int main(){
    pid_t parent_pid;
    pid_t pid;
    int i = 0;
    int return_val; //we're not going to use this, but need it to call sigwait()

    sigset_t set;
    sigfillset(&set);
    sigprocmask(SIG_BLOCK, &set, NULL);

    parent_pid = getpid();
    fprintf(stderr,"I am main process, here comes my pid %u\n",getpid());

    if (0>pipe(_pipe)) fprintf(stderr,"Error when creating pipe");

    //Start creating child processes
    while (i < N){
            pid = fork();
            if (pid == 0){
                close(_pipe[1]);
            break;
        }
        else{
            fprintf(stderr,"Created child with pid %u\n",pid);
            children[i] = pid;
            write(_pipe[1],&pid,sizeof(pid_t));
        }
        i = i+1;
    }

    i = 0;

    // What main process does
    if (pid>0){
        close(_pipe[0]);
        close(_pipe[1]);

        //sleep(2);

        // Main process sends signal to each child
        while(i < N){           
            kill(children[i],SIGUSR1);
            fprintf(stderr,"Sent SIGUSR1 to child %u\n",children[i]);
            // .. Now just wait for SIGUSR2 arrival
            sigwait(&set, &return_val);

            i = i+1;
        }
    }
    // What children do
    else{
        // Wait for main process SIGUSR1 delivery
        sigwait(&set, &return_val);

        fprintf(stderr, "SIGUSR1 arrived child %u from its father\n",getpid());

        // Once SIGUSR1 has arrived, pipe is read N times
        while((i < N) && (read(_pipe[0],&pid,sizeof(pid_t))>0)){
            children[i] = pid;
            i = i+1;
        }
        close(_pipe[0]);

        // After reading pipe, a reply is sent to parent process
        kill(parent_pid,SIGUSR2);
    }
    
    return 0;
}