I am not understanding how the alarm() works. In this case the function waits for the 5 seconds, if there is not any event the signal is being sent and is returned NULL pointer. What confuse me, is that if I change the two lines between them below, the functions returns immediately.
jmp_buf buff;
void handler(){
longjmp(buff,1);
}
char* tfgets(char * str, int n ,FILE * stream){
char *result;
if (!(setjmp(buff))){
if(signal(SIGALRM, handler) == SIG_ERR){
char * str= "Signal cant be added";
write(STDOUT_FILENO,str,strlen(str));
}
alarm(5);
return fgets(str,n,stream); // this is the line to be changed with the one below
}else{
return NULL; //this one
}
}
int main(int argc, char** argv, char**envp){
char buf[100];
char* input = tfgets(buf, 100, stdin);
if (input == NULL) {
printf("not typed");
}else {
printf("typed");
}
}
CodePudding user response:
If I understand you correctly, you're wondering why fgets
doesn't return immediately so that your tfgets
function can return immediately?
That's because fgets
will block until it has a line of input, it will simply not return.
Hence the alarm
is needed as a timeout: If the user doesn't write a line of input within five seconds, the input is canceled.