Calling close(sock) in one thread doesn't make recv(sock,...) return

Discussion in 'Linux Networking' started by Boris Bak, Jan 31, 2004.

  1. Boris Bak

    Boris Bak Guest


    I am running a library on Red Hat 8.0.

    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?

    Thanks for you help!

    Boris Bak, Jan 31, 2004
    1. Advertisements

  2. Boris Bak

    Cameron Kerr Guest

    You're running an unsupported version of RH, you should upgrade.
    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, Feb 1, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.