Wednesday, October 30, 2013

To Implement Inter Process Communication using Pipes

/*
To Implement Inter Process Communication using Pipes
*/

#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main()
{
        int fd[2],n,status;
        char buff[100];
        pipe(fd);
        if(pipe (fd)<0)
        {
                printf("Cannot create a pipe.....");
                exit(0);
        }

        else
        {
                switch(fork())
                {
                        case -1:
                                printf("\nFork error...");
                                exit(0);
 
                        case 0:
                                //child process read data from buffer

                                printf("\nRunning child process...");
                                printf("\nBefore read is performed...");
                                read(fd[0],buff,100);
                                printf("\nThe data read from the buffer is:\t %s",buff);
                                break;

                        default:
                                //parent process writes to buffer

                                printf("\nRunning parent process...\n");
                                printf("\nWriting...\n");
                                write(fd[1],"Welcome to HOME....",60);
                                wait(&status);
                                printf("\nWriting is over...\n");
                                break;
                }
        }
    return(0);
}



/*
Output:
Running child process...

Running parent process...

Writing...
Before read is performed...
The data read from the buffer is:        Welcome to HOME....
Writing is over...
*/

No comments:

Post a Comment