I know scanf waits for input. But in this program I have written it is printing hello in an infinite loop. Its not waiting for me to enter.
#
The scanf
function on POSIX platforms somewhere in its implementation is using the read
system call. When the timer signal is happening then the read
call will be interrupted and return with an error (EINTR
), which in turn leads to scanf
returning as well. You can check this by checking what scanf
returns. In this case it should return EOF
with errno
still set to EINTR
.
A simple solution to this is to ask the signal to restart the interrupted system call. This is done by adding the SA_RESTART
flag in the sigaction
structures sa_flags
member:
sa.sa_flags = SA_RESTART;
More information can be found in e.g. this POSIX sigaction reference.