Is there any difference between socketpair and pair of unnamed pipes?

删除回忆录丶 提交于 2020-11-30 02:57:31

问题


I would like to know not only user-side differences, but differences / common parts in Linux kernel implementation as well.


回答1:


  • pipes are unidirectional, so you need two pipes to have bidirectional communication, whereas a socketpair is bidirectional.

  • pipes are always stream-oriented, whereas socketpairs can be datagram-oriented.

  • socketpairs are normal AF_UNIX sockets, which means that ancillary messages like SCM_RIGHTS and SCM_CREDENTIALS can be passed over them.

In the kernel, pipes are implemented in the filesystem code and socketpairs in the networking code.




回答2:


The shutdown() and SCM_RIGHTS capabilities of socketpairs are needed to implement race-proof communication with subprocesses in a multithreaded program.

Pipes can be duplicated by accident in case several threads pipe() and fork() at the same time; in that case, the write end of the pipe may never get closed and EOF may never occur on the read end, causing deadlock. Even for those programs that use fork() for subprocesses only (ie all fork()s are promptly followed by execve() in the child), pipe capture by a concurrent fork() still races with setting the FD_CLOEXEC bit, barring use of the non-portable Linux pipe2() system call that accepts O_CLOEXEC.

Solving this hazard in a portable way, also for programs that fork() without then calling execve(), involves socketpairs:

  • For an outbound channel (ie, writing from the main program to the subprocess): use a socketpair instead of a pipe and call shutdown() before close() from the parent to cause a race-proof EOF condition, regardless of whether the file descriptor was duplicated.
  • For an inbound channel (ie reading from the subprocess), create a pipe in the child (so that the write end is never visible in the parent for accidental duplication) and send only the read end to the parent over a socketpair with an SCM_RIGHTS message.


来源:https://stackoverflow.com/questions/1583005/is-there-any-difference-between-socketpair-and-pair-of-unnamed-pipes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!