Our task is to develop an application that creates a child process. The parent process then waits 3 seconds (we are not allowed to use sleep in the parent process) and sends a SIGUSR2 signal followed by a SIGUSR1 signal. After that, the parent sends the SIGUSR1 signal periodically (3 seconds) to the child until it terminates. Upon child termination it prints Parent done and exits. We should implement this behaviour using alarm() and pause().
The child process should block the signal SIGUSR2 for 13 seconds. Upon receiving SIGUSR1 it should print Received SIGUSR1. Upon receiving SIGUSR2 it prints Child done and exits. My approach to implement this is the following:
Please note: the SIGUSR2 signal is only sent once, until now I did not implement that and it is sent each time along with the SIGUSR1 signal.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <stdarg.h>
static pid_t chld;
void init_signal(struct sigaction* action, void (*handler)(int));
void init_sigset(sigset_t* set, int signum);
void bind_signal(struct sigaction* action, int n, ...);
void par_signal(int signum);
void chld_signal(int signum);
int main(){
chld = fork();
struct sigaction action;
if (chld == -1){
fprintf(stderr, "Failed to create child process.\n");
return EXIT_FAILURE;
} else if (chld == 0){
init_signal(&action, &chld_signal);
bind_signal(&action, 3, SIGUSR1, SIGUSR2, SIGALRM);
sigset_t sig;
init_sigset(&sig, SIGUSR2);
sigprocmask(SIG_BLOCK, &sig, NULL);
alarm(13);
pause();
}
init_signal(&action, &par_signal);
bind_signal(&action, 2, SIGALRM, SIGCHLD);
alarm(3);
pause();
}
void init_signal(struct sigaction* action, void (*handler)(int)){
action->sa_flags = 0;
action->sa_handler = handler;
sigemptyset(&action->sa_mask);
}
void init_sigset(sigset_t* set, int signum){
sigemptyset(set);
sigaddset(set, signum);
}
void bind_signal(struct sigaction* action, int n, ...){
va_list args;
va_start(args, n);
for (int i = 0; i < n; i++){
int signum = va_arg(args, int);
sigaction(signum, action, NULL);
}
va_end(args);
}
void par_signal(int signum){
if (signum == SIGALRM){
kill(chld, SIGUSR2);
kill(chld, SIGUSR1);
alarm(3);
pause();
} else if (signum == SIGCHLD){
printf("Parent done\n");
exit(EXIT_SUCCESS);
}
}
void chld_signal(int signum){
if (signum == SIGALRM){
sigset_t sig;
init_sigset(&sig, SIGUSR2);
sigprocmask(SIG_UNBLOCK, &sig, NULL);
pause();
} else if (signum == SIGUSR1){
printf("Received SIGUSR1\n");
pause();
} else if (signum == SIGUSR2){
printf("Child done\n");
exit(EXIT_SUCCESS);
}
}
It works apart from the fact, that only the first signal of the parent process is received by the child. I figure this has something to do with my usage of pause respectively alarm. Do you have any idea what I am doing wrong?
The link to the exercise tasksheet can be found here (Task 3).