I would like to know not only user-side differences, but differences / common parts in Linux kernel implementation as well.
A socket pair consists of a pair of connected (but unnamed) sockets. It is very similar to a pipe and is used in much the same way. Socket pairs are created with the socketpair function, declared in sys/socket. h .
What is the difference between socket and pipe? A socket is a part of the OSI model that enables communication between different layers. Pipes are used in processing in the CPU. Communication in socket is bi directional while it's unidirectional in pipes.
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.
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:
shutdown()
before close()
from the parent to cause a race-proof EOF condition, regardless of whether the file descriptor was duplicated.SCM_RIGHTS
message.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With