Home > OS >  Are POSIX socket disconnection or error conditions atomic and thread-safe?
Are POSIX socket disconnection or error conditions atomic and thread-safe?

Time:01-18

While looking for a duplicate for this question I started to wonder about what would happen if the peer closes the connection, or if there's a network error.

This is the scenario:

A program which uses a TCP connection, and uses two threads:

  • One thread that calls read or recv;
  • And one thread that calls write or send

If the peer closes the connection the behavior for the two threads would be different and there are no guarantees which of the threads would be the first to detect the event.

I also haven't seen anything about events like connection closes by peer, or network error events, being atomic.

Are peer closing the connection as well as error handling for multi-threaded processes specified by POSIX? Will the behavior of a process like in the describes scenario be well-defined?

CodePudding user response:

If the peer closes the connection the behavior for the two threads would be different and there are no guarantees which of the threads would be the first to detect the event.

Correct. There are no guarantees. Indeed, they could "detect"the event simultaneously.

I also haven't seen anything about events like connection closes by peer, or network error events, being atomic.

I'm not sure what you mean by atomic. But these events are all things that either happen or they don't.

Are peer closing the connection as well as error handling for multi-threaded processes specified by POSIX?

POSIX doesn't specify error handling; i.e. what application code does when it is notified of one of the above events. But the circumstances in which application code is notified are (to a degree) specified by POSIX. For example, a thread that makes a read syscall on a socket will get an error (a -1 result and a code in errno) if there is no unread data AND a "connection closed by peer" event occurs or has already occurred. (I will leave it to you to read the POSIX specs and syscall manual entries to judge how precise and detailed they are.)

To my knowledge there is nothing thread specific about any of this, and there are no thread-safety concerns for the syscalls themselves.

Will the behavior of a process like in the describes scenario be well-defined?

Yes, though you should make your own judgement on clarity, etc of the related specs.

  • Related