I have found a problem where it asks to explain the behaviour of the following program:
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void sig_alrm(int n) {
write(2, "ALARM!\n", 7);
return;
}
int main() {
int fd[2], n;
char message[6], *s;
s = "HELLO\n";
signal(SIGALRM, sig_alrm);
pipe(fd);
if (fork() == 0) {
close(fd[1]);
alarm(3);
while ((n = read(fd[0], message, 6)) > 0);
alarm(0);
exit(0);
}
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
while (1)
write(1, s, 6);
}
It's basically a parent process with a shared pipe sending HELLO\n constantly via pipe to a child. The child sets up a SIGALRM
in three seconds which will be caught by the sig_alrm function, and then proceeds to read indefinitely from the pipe.
If I understand correctly, SIGALRM
should interrupt the read()
system call, causing it to error out upon arriving, which would in turn cause the child to exit with an instant alarm with default behavior, and the parent to end too due to a SIGPIPE
.
The problem is that I attempted to run the code, and both processes continue to read and write from the pipe happily after the SIGALRM
arrives to the child.
Is there something I misunderstood from signal behaviors?