I am working on a pthread multi-threaded code and each thread is calling read() on a file descriptor. read() is a blocking call so it waits for data. But i want it to wait only for 3 secs to wait for data.
I thought of using alarm() and hadling SIGALRM but if I raise alarm in one thread, all the threads will got that SIGALRM signal and all of them will relinquish read. How can i do it?
Use the
selectcall for that. It has one argument that allows you to specify a timeout.The Linux man page for
selecthas a sample usage, and you’ll find lots of examples here and elsewhere on the web.If you’re not worried about portability, there are more modern/featureful options.
epollfacility. The man page has sample code, this question lists a couple of blogs with other usage information.kqueue.You might want to look into libraries to abstract all that out. libevent is worth a look, and wraps most of the above OS-specific interfaces.