Tech Blog 3: Simple communication from child process to parent process using Pipe

Program solution in C:

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<string.h>
#include<sys/wait.h>

int main()

{
int pipefd[2];
pid_t ret;
char readbuff[45];
char writebuff[45];
int byte;
int fdout;
int i;
int status;

pipe(pipefd);
/************************* creates pipe with pipefd[0] as read end and
pipefd[1] as write end***************************************/

ret = fork();

if(ret < 0)
{
perror(“can’t create a process”);
}

if(0 == ret)  /****** child **********/
{
close(pipefd[0]); /********* close the read end of  the pipe ************/

for(i=0 ; i<5 ; i++)
{
printf(“plz enter the string\n”);
memset(writebuff,”,45);
fgets(writebuff,44,stdin);

/* byte = read(0,writebuff,44);
if(-1 == byte)
{
printf(“can’t read\n”);
perror(“can’t read\n”);

}
*/
byte = write(pipefd[1],writebuff,(strlen(writebuff)+1));

if(-1 == byte)
{

printf(“can’t write”);
perror(“cannot write”);
}
} /*End of for loop*/
printf(“i m in child process\n”);
close(pipefd[1]);

exit(0);

}

else   /******** PARENT ***********/

{
close(pipefd[1]);
wait(&status);

fdout = open(“outfile”,O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU);
if(0> fdout)
{
printf(“file for writing is not created\n”);
perror(“write file error”);
}

for (i=0 ; i<5 ; i++)

{
while( (byte = read(pipefd[0],readbuff,45)) >0)
{

write(fdout,readbuff,byte);
}

}
close(pipefd[0]);
close(fdout);
return 0;

}
}

 

Posted on February 13, 2013, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: