8

When a process binds a name to a TCP socket (i.e. ip:port pair) and exits, it doesn't has to explicitly cleanup anything: another process can reuse the same ip:port. Same with the abstract UNIX sockets on Linux (when sun_path starts with zero byte). However, when using traditional UNIX sockets, one has to unlink it after it is no longer needed (or before bind-ing, which is not very good since you can remove something important).

According to my observations, once the last file descriptor referring to the UNIX socket is closed, the socket file is useless garbage: open returns ENODEV, connect returns ECONNREFUSED, and bind returns EADDRINUSE. The only thing one can (and has to) do is unlink.

Shouldn't OS remove socket file from file system automatically when it's no longer used?

Oleg Andriyanov
  • 5,069
  • 1
  • 22
  • 36
  • 3
    I might argue that the correct thing for the system to do would be to allow rebinding to a lingering socket file, just like rebinding to a TCP port is allowed. This would actually be nice, since it would be possible to manually set socket permissions and have them remain. Nevertheless, it would be interesting if anyone knows the reason for the current behavior. – Dolda2000 Apr 14 '17 at 22:53
  • Questions about the design of Unix would be more appropriate for unix.SE than SO. – Barmar Apr 14 '17 at 23:07
  • 1
    Socket files never get opened by any process and therefore there is no inodes or descriptors to check if it is in use. _**Names in the UNIX domain are only used for establishing connections. They are not used for message delivery once a connection is established. Therefore, in contrast with the Internet domain, unbound sockets need not be (and are not) automatically given addresses when they are connected.**_ - excerpt from http://osr507doc.sco.com/en/netguide/dusockD.binding_names.html – alvits Apr 14 '17 at 23:42
  • You would be better off asking this question on unix.stackexchange.com or serverfault.com – Rob Apr 14 '17 at 23:45
  • @Dolda2000 Makes sense. Surprisingly, setting `SO_REUSEADDR` before binding doesn't allow to rebind to the existing socket. – Oleg Andriyanov Apr 14 '17 at 23:52
  • @alvits I think this excerpt means that once UNIX domain connection is established, the socket which **`connect`**-ed doesn't has a name, i.e., `getsockname` returns nothing, as opposed to `AF_INET` sockets where connected sockets are assigned some IP address and random port. – Oleg Andriyanov Apr 14 '17 at 23:57

0 Answers0