IPC – pipes

Inter Process Communication 

Pipes


SYSTEM CALL:

pipe() – create a pipe and puts the file descriptors for the reading and writing ends of the pipe into fd[0] and fd[1] (respectively).

Prototype: int pipe (int fd[2])

Returns: If successful, pipe returns a value of 0. On failure, -1 is returned.

Pipe Read and Write function:

Prototype   :   int read(int fd, char *Buff, int NumBytes);

Parameters :   int fd;

char Buff[50];

Example    :   read(fd, Buff, sizeof(Buff));

Prototype   :   int write(int fd, char *Buff, int NumBytes);

Parameters :   int fd;

char Buff[]=”Welcome”;

Example    :   write(fd, Buff, strlen(Buff)+1);


// Program :

// 2. IPC Using Pipes

#include<stdio.h>

#include<unistd.h>

#include<string.h>

main()

{

int p1[2], p2[2];

char str[25];

printf(“\nIPC USING PIPES\n”);

printf(“ENTER THE STRING : “);

scanf(“%s”,str);

pipe(p1);

pipe(p2);

write(p1[1],str,sizeof(str));

int a=fork();

if(a==0)

{

printf(“\n Child Process :”);

read(p1[0],str,sizeof(str));

printf(“\n\tMessage received : %s\n”,str);

strcat(str,” Returned”);

write(p2[1],str,sizeof(str));

}

else

{

wait();

printf(“\n Parent Process :”);

read(p2[0],str,sizeof(str));

printf(“\n\tMessage received : %s\n\n”,str);

}

}