为什么可以用unix domain socket把fd从child传给father?

Why unix domain socket can be used to transfer fd from child to father?

我知道如果 unix 进程分叉,child 进程可以使用父进程的 fd。这是继承:但反之则不然。

虽然unix高级编程资料说如果我们使用unix domain socket,我们不仅可以将fd从child传递给父亲,而且还可以在进程之间传递。

这很奇怪:

an fd is only meaningful within one process, in different process, same fd value could mean very different.

Then how could unix domain socket really transfer fds between processes? I mean the integer (4 bytes) can be transferred by any means, but it doesn't seem to make sence that one process can operate another process's fd?

有什么解释吗?

你真的应该亲自尝试一下。正如 unix(7) 的手册页中所述:

SCM_RIGHTS Send or receive a set of open file descriptors from another process. The data portion contains an integer array of the file descriptors. The passed file descriptors behave as though they have been created with dup(2).

这意味着收到的fds和发送的fds不一样,它们就像新创建的fds,但从内核的角度来看它们实际上是一样的。