Unix Programming - Avoiding hang when read blocks

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > January 2005 > Avoiding hang when read blocks





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Avoiding hang when read blocks
Ian Pilcher

2005-01-22, 5:49 pm

I am working on a multi-threaded program that reads data from a named
pipe (using fgets). I would like to guard against the program hanging
if reading from the pipe blocks.

What's the best (and hopefully most convenient) way to do this? I'd
like to set some kind of alarm which will interrupt the read with a
signal if it blocks for too long, but everything I read indicates that
mixing signals and threads is a big no-no.

Ideas? Thanks!

--
========================================
================================
Ian Pilcher i.pilcher@comcast.net
========================================
================================
Sean Burke

2005-01-22, 5:49 pm


Ian Pilcher <i.pilcher@comcast.net> writes:

> I am working on a multi-threaded program that reads data from a named
> pipe (using fgets). I would like to guard against the program hanging
> if reading from the pipe blocks.
>
> What's the best (and hopefully most convenient) way to do this? I'd
> like to set some kind of alarm which will interrupt the read with a
> signal if it blocks for too long, but everything I read indicates that
> mixing signals and threads is a big no-no.


You can make the fd nonblocking, and call select with a timeout.
In this case, you don't want to use fgets, since mixing stdio
with operations on the underlying fd can lead to confusion.

For that matter, you can arrange for another thread to send a
signal using pthread_kill that will interrupt the read (or write)
if it blocks. I've used this method successfully, but be careful
if you are using thread cancellation - fgets is a cancellation
point, so you must cancel the timeout in a cleanup handler, or
risk having the signal sent to a new thread that reuses the old
thread id.

For multithreaded code, it's nice to have a single thread that
can handle numerous such scheduled tasks. There is a timer
task package in the Nifty library that serves this purpose,
which is free to use:

ftp://ftp.xenadyne.com/pub/Nifty.tgz

-SEan


DINH Viet Hoa

2005-01-22, 8:48 pm

Ian Pilcher wrote :

> I am working on a multi-threaded program that reads data from a named
> pipe (using fgets). I would like to guard against the program hanging
> if reading from the pipe blocks.


select() is your friend.

Same function can be used to prevent write on pipe to block.

--
DINH V. Hoa,

"s/^\(\(\\.\|[^\[]\|\[\(\^.\|[^^]\)[^]]*\]\)*\)\(\\[^\*[]\)/\1\\\4/"
-- Stéphane CHAZELAS

Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com