Before voting to close, please read, I know that there are similar questions (:
Here's my situation - I have an application, that is multithreaded. So, lets say I have 10 threads. All of them read from the same file descriptor (it's actually a socket ). And in a very rare situation, when a critical error occurs, the socket should be shutdown
by one of the threads. The thing is, that any of these thread can do this. If the closing of the socket has failed, _Exit( FAILURE )
is executed (I know, that this sounds like an awful design or problem in the code, but it actually isn't, as this is caused by a non-opensource 3rd party lib, that has a bug).
And here's the problem situation - it's possible all of them to try to shutdown
the socket in the same time. And one closes it, but the others cannot close it (shutdown
returns -1, as the socket is already closed) and the bad _Exit( FAILURE )
is executed and that ruins everything.
Obviously, I need an additional check - if the socket is already closed (it's possible all threads to have failed shutting down the socket for some reason, and then at least one must execute _Exit
, that's why checking the return code of shutdown
is not enough).
Well, I found this question and it looks like that's exactly what I'm trying to do. But I know, that any kind of system calls take time (of course ) and it's OS dependent when exactly the socket will be closed.
And here's the question - how can I make difference if a socket is already closed or it cannot be closed for some reason? Will the fcntl
ensure me, that if one thread has closed the socket and at the same time if other thread try to shutdown
the socket, it will fail and then, if I make this check ( with fcntl
), this will work for me?
I also saw the other answers like: "you can use select
or poll
", but they are still system calls and I don't know if they will be the better choice. I also don't know how exactly to use them, but it's not a big deal, I guess.
Thanks!
I can also check the errno
set by shutdown
, but what does "connected" mean? And what is the difference between "connected" and "not a valid descriptor"
ENOTCONN
The specified socket is not connected.
Also, what bothers me is, that the FD, I'm trying to close, could be invalid, as I take it from /proc/net/tcp
mapped with proc/PID/fd
and I don't know if all files will look like the way, they look on my OS (the OS will be for sure RHEL4 or RHEL5, if that matters)
Doh! It's damn long, but I can't explain it shorter.