Why do I need socketpair() when I have socket() with AF_UNIX?

一曲冷凌霜 提交于 2021-02-08 07:39:42

问题


What confuses me is that given that sockets are bi-directional, why can't I just open 1 socket with socket() on the client and one on the server and let them communicate over this single socket?

What would be a common use case that I would need a pair of sockets?


回答1:


So what is the common use case that I would need a pair of sockets?

Typically that you want bidirectional communication between a parent and child process (or sometimes between threads in the same process).

It's like a bidirectional equivalent of pipe, and avoids exposing an AF_UNIX path, or any other publicly-visible address, for something internal to your program.

There's a worked example here.




回答2:


socketpair creates two sockets which are already connected to each other. A common use case is the communication between a parent and a child process: the parent creates the socket pair, forks the child and then child and parent can communicate through their end of the socket pair with each other.



来源:https://stackoverflow.com/questions/64214231/why-do-i-need-socketpair-when-i-have-socket-with-af-unix

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