I'm tyring to write a program that every 5 seconds checks all the signals received and varies its output depending on them. My main issue is making the code actually wait the 5 seconds, since the function sleep() gets interrupted as soon as a signal is processed. What I have tried to do is fork the program into two processes, and have only the child work with the signals, and communicate them by a pipe. The issue is that, being the pipe blocking, after the first 5 second, the parent will just try to read there, basically making the sleep useless.
In theory I should be able to solve such problem just using the libraries I included (or in alternative with pthread library,it's an assignment), otherwise I saw I could use other libraries to make the pipe not blocking, but at the moment I'm short of ideas on how to fix this (I also tried a failed attempt with thread).
I attach the code for reference, thanks in advance.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int p[2];//pipe
void sigHandler (int sig) {
char c;
switch (sig) {
case SIGUSR1:
c = '1';
break;
case SIGUSR2:
c = '2';
break;
case SIGALRM:
c = '0';
break;
case SIGSTOP:
exit (0);
break;
}
write(p[1], &c, sizeof(char));
}
int main(int argc, char **argv) {
int signals[3], sig, i;
for (i=0; i< 3; i++) {
signals[i] =0;
}
pid_t pid;
char csig;
pipe(p);
/*fork code*/
pid = fork();
/*parent*/
if (pid) {
close(p[1]);
int proceed = 1;
/*cycle keeps on indefinitely*/
while (proceed) {
sleep(15); //increased the time so I have time to send signals
while (read(p[0], &csig, sizeof(char)) > 0) {
sig=atoi(&csig);
signals[sig]++;
/*if alternating sigals, error*/
if (signals[1] && signals[2]) {
printf("Error: alternating SIGUSR1 and SIGUSR2\n%d\t%d\n", signals[1], signals[2]);
}
/*if 2 consecutive signals, success*/
if (signals[sig] == 2) {
printf("Success: two consecutive SIGUSR1 or SIGUSR2\n");
}
/*if three consecutive signals, exit*/
if (signals[sig] == 3) {
kill(pid, SIGSTOP);
proceed = 0;
break;
}
/*make 0 any non repeating signal != sig*/
for(i = 0; i< 3; i++) {
if (i != sig) {
signals[i] = 0;
}
}
}
}
/*child*/
} else {
close(p[0]);
signal(SIGUSR1, sigHandler);
signal(SIGUSR2, sigHandler);
signal(SIGALRM, sigHandler);
signal(SIGSTOP, sigHandler);
while (1) {
sleep(5); //no need to do anything else
}
exit(1);
}
return 0;
}