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
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.
- 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 thisSTREAMtopic you quote is a special case that doesn't apply for normal TCP?nh2– nh22017-07-05 20:04:50 +00:00Commented 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 ifSO_LINGERis enabled with a non-0 timeout. Another useful resource is this, discussingSO_LINGERbehaviour accross platforms.nh2– nh22017-07-05 20:08:49 +00:00Commented Jul 5, 2017 at 20:08 - 1The 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_LINGERis exactly a case whereclose()can block, and your sources agree. The question is "canclose()block?", not about the default behaviour. The example at the bottom of the answer was unhelpful, though.Michael Homer– Michael Homer2017-07-05 20:51:13 +00:00Commented 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.nh2– nh22017-07-06 14:37:37 +00:00Commented Jul 6, 2017 at 14:37