Question:
How to interrupt a blocked read() system call in linux/unix.?
anonymous
2008-04-08 16:11:43 UTC
Hi, thanks ahead for any info,
I have a while loop that calls the system read() function.
read() blocks while waiting for input. I need to implement a timer that would unblock read() after 3 seconds (given that read did not actually read any input). I have a timer implemented via setitimer() system call. I wondering if I should be using something like sigaction, or some other signal call. All this is in Linux. Thanks for a any tips!!
Three answers:
Michael Safyan
2008-04-08 16:20:26 UTC
Yes. You need to use "sigaction" in order to set the signal handler for the SIGALRM or SIGVTALRM signal, depending on which alarm you use with the setitimer function.



By default, the signal handler will interrupt the execution of the read function, unless you use the SA_RESTART flag for the sigaction signal handler. When the read is interrupted, read will return with a value of -1 and errno will be set to EINTR.
anonymous
2016-12-16 18:38:16 UTC
Linux Select System Call
Sergey P
2008-04-12 12:44:02 UTC
System call select() will help you. Here is sample code (not tested) that may help you (see man select for more info):



fd is a file descriptor that you want to read.



struct timeval time;

fd_set set;



time.tv_sec = 3;

time.tv_usec = 0;



FD_ZERO(&set);

FD_SET(fd, &set);

if (select(fd+1, &set, NULL, NULL, &time, NULL) > 0) {

// we read something from fd before 3 seconds exceeded

}

else {

// either error or 3 seconds exceeded

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...