4

For example, if you close a pipe or socket that still has data in its write buffer that hasn't been read by the process on the other end, does close() block until the data is read or the other process dies?

1 Answer 1

5

Yes, close can block:

If O_NONBLOCK is not set and there have been no signals posted for the STREAM, and if there is data on the module's write queue, close() shall wait for an unspecified time (for each module and driver) for any output to drain before dismantling the STREAM.

And:

If fildes refers to a socket, close() shall cause the socket to be destroyed. If the socket is in connection-mode, and the SO_LINGER option is set for the socket with non-zero linger time, and the socket has untransmitted data, then close() shall block for up to the current linger interval until all data is transmitted.

4
  • This answer conflicts with this Quora answer that says that by default close() returns immediately and "all data is sent but this occurs asynchronously—in the background". It also conflicts with this comprehensive article. Is it possible that this STREAM topic you quote is a special case that doesn't apply for normal TCP? Commented Jul 5, 2017 at 20:04
  • On this page I have found: "A STREAMS subsystem is available for Linux, but you need to add it yourself. It is not usually included by default.". So I suspect that this answer is inaccurate. close() can block, but only if SO_LINGER is enabled with a non-0 timeout. Another useful resource is this, discussing SO_LINGER behaviour accross platforms. Commented Jul 5, 2017 at 20:08
  • 1
    The first paragraph is marked obsolete in POSIX, but you could still encounter it. I don't know what your objection to the second is; setting SO_LINGER is exactly a case where close() can block, and your sources agree. The question is "can close() block?", not about the default behaviour. The example at the bottom of the answer was unhelpful, though. Commented Jul 5, 2017 at 20:51
  • OK, thanks, that clarifies it. I mainly confused by the first paragraph. I have no objection to the second. Commented Jul 6, 2017 at 14:37

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.