c - Why does alarm() cause fgets() to stop waiting? -


i playing around signals in c. main function asks input using fgets(name, 30, stdin), , sits there , waits. set alarm alarm(3), , reassigned sigalrm call function myalarm calls system("say pay attention"). after alarm goes off, fgets() stops waiting input , main fn continues on. happens if change myalarm set variable , nothing it.

void myalarm(int sig) {     //system("say pay attention");     int x = 0; }  int catch_signal(int sig, void (*handler)(int)) { // when signal comes in, "catch" , "handle it" in way want     struct sigaction action;  // create new sigaction     action.sa_handler = handler;  // set it's sa_handler attribute function specified in header     sigemptyset(&action.sa_mask);  // "turn signals in sa_mask off?" "set sa_mask contian no signals, i.e. nothing masked?"     action.sa_flags = 0; // not sure, looks aren't using of available flags, whatever may      return sigaction(sig, &action, null);  // here reassign- when sig received, it'll action tells }  int main() {      if(catch_signal(sigint, diediedie)== -1) {         fprintf(stderr, "can't map sigint handler");         exit(2);     }      if(catch_signal(sigalrm, myalarm) == -1) {         fprintf(stderr, "can't map sigalam handler\n");         exit(2);     }      alarm(3);      char name[30];     printf("enter name: ");     fgets(name, 30, stdin);      printf("hello, %s\n", name);      return 0;  } 

why alarm() make fgets() stop waiting input?

edit: added code catch_signal function, and, per 1 of comments, used sigaction instead of signal, issue persisted.

the answer going os/system specific.

(as stated retr0spectrum) fgets() function makes system calls, such read(). system calls can terminate if signal detected. in case of question, fgets() function has made system call (likely read() system call) read character stdin. sigalrm causes system call terminate, , set errno eintr. causes fgets() function terminate, without reading characters.

this not unusual. it's how os implements signals.

to avoid problem, wrap fgets() function in loop this:

do {    errno=0;    fgets(name, 30, stdin);    } while(eintr == errno); 

it require you: #include <stdio.h>

(as suggested tonyb).


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -