Pipes Example Code For Linux Process Synchronizaion

Pipe is a buffer of fixed size written by one related process and read by another related process. where related process means, parent and child process.
Usage : int pipe(int fildes[2])
creates a pipe and returns two file descriptors, fildes[0] and fildes[1] for reading and writing.
mutual exclusion is handled by operating system, ie only one process at a time can read or write to pipe. If one process is reading or writing on pipe other process will wait.
processes sharing the pipe must have same parent in common and are unaware of each other’s existence

Pipe example

int n;
int   pipefd[2];
char buff[100];
if (pipe(pipefd) < 0)       // create a pipe
perror(“pipe error”);
printf(“read fd = %d, writefd = %d\n”, pipefd[0], pipefd[1]);
if (write(pipefd[1], “hello world\n”, 12) !=12) // write to pipe
perror(“write error”);
if ((n=read(pipefd[0], buff, sizeof(buff))) <=0) //read from pipe
perror(“read error”);
write(1, buff, n );   /* write to stdout */
read fd = 3, writefd = 4
hello world
default FD for any process under Linux is from 0, 1 and 2 ie for STDIN, STDOUT and STRERR, whatever new descriptors are created will be assigned FD greater than 2. So read FD for pipe is 3 and write FD for Pipe is 4.
Number of View :1176

Tags: , ,

  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache