In: Computer Science
Write a “C” program(Linux) that creates a pipe and forks a child process. The parent then sends the following message on his side of the pipe “I am your daddy! and my name is <pid-of the-parent-process>\n”, the child receives this message and prints it to its stdout verbatim. The parent then blocks reading on the pipe from the child. The child writes back to its parent through its side ofthe pipe stating “Daddy, my name is <pid-of-the-child>”. The parent then writes the message received from the child to its stdout. Make sure the parent waits on the child exit as to not creating orphans or zombies. Include Makefile.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main()
{
// We use two pipes
// First pipe to send input string from parent
// Second pipe to send concatenated string from
child
int fd1[2]; // Used to store two ends of first
pipe
int fd2[2]; // Used to store two ends of second
pipe
pid_t p;
if (pipe(fd1)==-1)
{
fprintf(stderr, "Pipe Failed"
);
return 1;
}
if (pipe(fd2)==-1)
{
fprintf(stderr, "Pipe Failed"
);
return 1;
}
p = fork();
if (p < 0)
{
fprintf(stderr, "fork Failed"
);
return 1;
}
// Parent process
else if (p > 0)
{
char concat_str[100];
char input_str[]="I am your daddy!
and my name is ";
char s[100];
close(fd1[0]); // Close reading end
of first pipe
int i=getpid();
sprintf(s, "%d", i);
strcat(input_str,s);
// Write input string and close
writing end of first
// pipe.
write(fd1[1], input_str,
strlen(input_str)+1);
close(fd1[0]); // Close reading end of first pipe
close(fd1[1]); // Close writing end
of first pipe
// Wait for child to send a
string
wait(NULL);
close(fd2[1]); // Close writing end of second pipe
// Read string from child, print
it and close
// reading end.
read(fd2[0], concat_str,
100);
printf("string received from child
in parent Process: %s\n", concat_str);
close(fd2[0]);
}
// child process
else
{
close(fd1[1]); // Close writing end
of first pipe
// Read a string using first
pipe
char parent_str[100];
read(fd1[0], parent_str,
100);
printf("string received from parent
in child process : %s\n", parent_str);
// Close both reading ends
close(fd1[0]);
close(fd2[0]);
char child_str[]="Daddy, my name is
";
char s[100];
int i=getpid();
sprintf(s, "%d", i);
strcat(child_str,s);
// Write concatenated string and
close writing end
write(fd2[1], child_str,
strlen(child_str)+1);
close(fd2[1]);
exit(0);
}
}