Showing posts with label Parent Child communication using pipes. Show all posts
Showing posts with label Parent Child communication using pipes. Show all posts

Sunday, March 24, 2013

Parent Child communication using pipes

penguin-centos-logoParent Child communication using pipes

This is the simplest of program that you can get.

Here the parent communicates to child over a pipe.

NOTE:
if the child wants to communicate to the parent then it will have to closes(fd[0]) and Parent will closes(fd[1]).

this will only work UBUNTU, LINUX(RedHat) , Solaris, FreeBDS etc all UNIX VERSIONS. DONT TRY to use it on any compiler like gcc,turbo c, etc...

Send data from Parent to Child over a pipe:
#include <apue.h>  
#include <sys/types>
#include <sys/wait.h>

int main(void)
{
int n;
int fd[2];
pid_t pid;
char data[]="Hello world";
char line[MAXLINE];

pid = fork();

if (pipe(fd) < 0)
printf("pipe error");
if (pid < 0) {
printf("fork error");
} else if (pid > 0) { /* parent */
close(fd[0]);
write(fd[1], data, strlen(data));
} else { /* child */
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}
exit(0);
}

 

Parent Child communication using pipes

penguin-centos-logoParent Child communication using pipes

This is the simplest of program that you can get.

Here the parent communicates to child over a pipe.

NOTE:
if the child wants to communicate to the parent then it will have to closes(fd[0]) and Parent will closes(fd[1]).

this will only work UBUNTU, LINUX(RedHat) , Solaris, FreeBDS etc all UNIX VERSIONS. DONT TRY to use it on any compiler like gcc,turbo c, etc...

Send data from Parent to Child over a pipe:
#include <apue.h>  
#include <sys/types>
#include <sys/wait.h>

int main(void)
{
int n;
int fd[2];
pid_t pid;
char data[]="Hello world";
char line[MAXLINE];

pid = fork();

if (pipe(fd) < 0)
printf("pipe error");
if (pid < 0) {
printf("fork error");
} else if (pid > 0) { /* parent */
close(fd[0]);
write(fd[1], data, strlen(data));
} else { /* child */
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}
exit(0);
}