View Single Post

  #2 (permalink)  
Old 02-01-2004
Cameron Kerr
 
Posts: n/a
Default Re: Calling close(sock) in one thread doesn't make recv(sock,...) return

Boris Bak <boris.bak@ni.com> wrote:
> Hi,
>
> I am running a library on Red Hat 8.0.


You're running an unsupported version of RH, you should upgrade.

> It has 2 threads. In one thread I do recv(sock,...), which blocks until
> data is received. When application that called the library exits, the
> library executes clean-up code as part of which it calls close(sock) on
> the same socket that recv(sock,...) was issued before. And then does
> pthread_join() to wait for the reading thread to finish
>
> What I notice is recv(sock,...) never returns, which makes my join()
> hang. If I press Ctrl-C, it seems to terminate the recv and allows the
> clean-up code to finish normally.
>
> Does anybody know a way to terminate a recv(sock,...), besides close()?
> And why does the close() don't do the job in the first place?


A couple of suggestions.

1) Just before you all close(), send yourself a signal that you have set
an empty signal handler to. That function doesn't need to do anything
but return. The side effect of that is that receiving signals will
interrupt signal calls, causing recv to return with -1, and errno being
EINTR. Close should then return pretty much immediately.

2) Use select() with a timeout to prevent recv() blocking infinately. Then
you just run select() in a loop, reading when you don't timeout and
there is something readable. This will cause a certain amount of lag
when you shutdown the application however (depending on the select()
timeout.) You would weigh this against the everhead caused by repeated
polling. A 1 second timeout should be plenty.

All in all, I would suggest using select() over the signal method, its
cleaner, and there are fewer complications when you don't mix signals
and threads.

You may get better advice on programming in
comp.os.linux.development.apps or comp.unix.programmer

--
Cameron Kerr
cameron.kerr@paradise.net.nz : http://nzgeeks.org/cameron/
Empowered by Perl!
Reply With Quote