There is a way to interrupt a call without resorting to ugly hacks (unlike what Paul R said). You should use sigaction() with sa_flags for 0 instead of signal() .
In addition, the signal manual (2) states:
Avoid using : use sigaction (2) instead.
#include <stdio.h> #include <signal.h> #include <string.h> #include <errno.h> static char done = 0; static void sigHandler(int signum) { done = 1; } int user_input() { return (getchar() == 'q') ? 0 : 1; } int main(void) { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sigHandler; sa.sa_flags = 0;// not SA_RESTART!; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); while (user_input() != 0 && !done) usleep(1000); printf("exiting\n"); return 0; }
Usually, after detecting and processing the signal, most (I'm not sure, if not all) system calls will be restarted. This way, after processing the sigint signal, your getchar function will continue as if nothing had happened. You can change this behavior by calling sigaction with sa_flags sa_flags=0 .
Thus, after processing SIGINT, getchar will return -1 , and errno will be set to "Interrupted system call" (I do not remember the name of the constant right now).
You will also have to rewrite the user_input () function to handle the case when returning -1. A.
source share