language: C (gcc-4.7.2)
date: 164 days 19 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#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;
}