1

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?

mohit jain
  • 397
  • 1
  • 3
  • 14

1 Answers1

5

Use the select call for that. It has one argument that allows you to specify a timeout.

The Linux man page for select has 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.

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.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
  • select is deprecated. epoll is what people use these days. –  Apr 15 '12 at 06:22
  • oh yes, i think this should work. I never considered that use of select() before. I never considered select() for any other thing than multiplexing. – mohit jain Apr 15 '12 at 06:24
  • @VladLazarenko: "deprecated" is a bit of a strong wording for that. `epoll` isn't portable, and `select` isn't going away any time soon. Sure there are more modern alternatives, but they're also (IMO) often harder to get right. – Mat Apr 15 '12 at 06:26
  • @Mat: For a portable solution you are better off with some library like libevent, though it has a bunch of its own disadvantages. But yeah - it is not portable and not all of the features may be available on older kernels, like eventfd is not in Android yet. But frankly, epoll is a lot more powerful and IMHO easier to work with than any select/poll. I think epoll and kqueue are worth talking about here and not only mentioning select. –  Apr 15 '12 at 06:30
  • @VladLazarenko: feel free to post an answer then :) – Mat Apr 15 '12 at 06:33
  • @Mat: I am too lazy for that, so you get a +1 and I go to bed :) –  Apr 15 '12 at 06:36
  • @VladLazarenko: :) Since I'm just waking up, I added a few more references. – Mat Apr 15 '12 at 06:54