My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.
The design I come up with is: the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.
Why would this happen and how can I fix this?
#include "csapp.h"
void handler() {
printf("lazy man\n");
kill(SIGKILL, getppid());
exit(0);
}
int main() {
char buf[100];
signal(SIGALRM, handler);
pid_t pid;
if ((pid = fork()) == 0) {
alarm(1);
} else {
fgets(buf, 100, stdin);
printf("%s", buf);
}
return 0;
}
~