Tuesday, September 20, 2011

difference between sockets and pipes

Comparing Sockets to Pipes

Before you are introduced to any socket functions, review the pipe(2) function call that you might already be familiar with. Let's see how the file descriptors it returns differ from a socket. The following is a function synopsis taken from the pipe(2) man page:

#include <unistd.h>
int pipe(int filedes[2]);

The pipe(2) function call returns two file descriptors when the call is successful. Array element filedes[0] contains the file descriptor number for the read end of the pipe. Element fileds [1] receives the file unit number of the write end of the pipe.

This arrangement of two file descriptors is suggestive of a communications link with file descriptors at each end, acting as sockets. How then does this differ from using sockets instead? The difference lies in that the pipe(2) function creates a line of communications in one direction only. Information can only be written to the file unit in filedes[1] and only read by unit filedes[0]. Any attempt to write data in the opposite direction results in the Linux kernel returning an error to your program.

#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);

Sockets, on the other hand, allow processes to communicate in both directions. A process is able to use a socket open on file unit 3, for example, to send data to a remote process. Unlike when using a pipe, the same local process can also receive information from file unit 3 that was sent by the remote process it is communicating with.

No comments:

Post a Comment