alecbz
alecbz

Reputation: 6488

Are read/writes to a socketpair completely synchronous or is there buffering?

Does the OS provide any kind of a buffer when using a socketpair for communication? Ie, if I do

int sv[2];
socketpair(PF_LOCAL, SOCK_STREAM, 0, sv);

will a write(sv[0], ...) block until a read(sv[1], ...) is also taking place? Or will some amount of data be stored somewhere in the OS even if a read was not taking place when the write occured?

Upvotes: 1

Views: 2344

Answers (1)

abligh
abligh

Reputation: 25119

There is no buffering in C for socketpair sockets like there is STDIO buffering with fopen. However, there is a buffer in your operating system. The buffer sizes can be set with setsockopt using SO_SNDBUF and SO_RCVBUF for send and receive just like any normal socket. The default values are operating system dependent. man -s7 socket will help here.

The buffering may be slightly dependent on socket type. For instance, I think with datagram sockets you are guaranteed atomicity. In most (all?) POSIX operating systems the only available address family is AF_UNIX. I believe you can use SOCK_STREAM or SOCK_DGRAM, and the buffering technique will depend on which of these you choose. From memory the SOCK_DGRAM will simply fail if you use more than the available buffer size (as the datagrams are transmitted atomically), whereas SOCK_STREAM will block; I'd check that before relying on it.

Upvotes: 2

Related Questions