#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
//Creating required pipe ends for read and write and variable to stroe pid and others value
int pid, pipeFileDescriptor[2], pipeCheck, status;
//Attaching File Descriptor to pipe.
pipeCheck = pipe(pipeFileDescriptor);
//If fails to attach then show error.
if(pipeCheck < 0){
printf(“Pipe error\n”);
exit(1);
}
//If Successfull then create child process using fork
pid = fork();
//If value in pid is -1 then it means that it failed to create child process, show error
if(pid == -1){
printf(“PARENT: Failed to create a process\n”);
exit(1);
}
//If pid is 0 means child process is created successfully
if (pid == 0)
{
//Code for child process
//Create character buffer to store vu id.
char buffer[50];
//Create variable to store digit value
int value;
//Printing pid, parent pid value
printf(“CHILD: I am child process!\n”);
printf(“CHILD: Here is my PID: %d\n”, getpid());
printf(“CHILD: My parent’s PID: %d\n”, getppid());
//Accepting vu student id from user and output it
printf(“CHILD: Enter your Student ID: “);
scanf(“%s”, buffer);
printf(“CHILD: Student ID is: %s\n”,buffer);
printf(“CHILD: I am writinng VU student to pipe\n”);
//Closing the read end and write the vu id from write end.
close(pipeFileDescriptor[0]);
write(pipeFileDescriptor[1], buffer, (sizeof(buffer)*50));
close(pipeFileDescriptor[1]);
//Taking the digit value from user until meets criteria
while(1){
printf(“CHILD: Please enter any value from 0 to 255: “);
scanf(“%d”, &value);
if(value >= 0 && value <= 255){
break;
}else{
printf(“CHILD: Not valid value.\n”);
}
}
//Printing good bye and child process exits from here.
printf(“CHILD: GoodBye!\n”);
}else{
//Create buffer to save value read from read end of pipe.
char buffer[50];
int noOfBytesRead;
//Waiting for child process to finish.
wait(&status);
//Showing general message of pid
printf(“PARENT: I am parent process!\n”);
printf(“PARENT: Here is my PID: %d\n”,getpid());
printf(“PARENT: Value returned by child process is: %d\n”,pid);
//Showing the vu id read from pipe.
printf(“PARENT: I am reading VU student id from pipe “);
//Closing the write end of pipe
close(pipeFileDescriptor[1]);
//Reading the vu id in buffer from read end and closing the read end.
noOfBytesRead = (int)read(pipeFileDescriptor[0], buffer, (sizeof(buffer)*50));
close(pipeFileDescriptor[0]);
//Printing the value in buffer.
printf(“%s\n”, buffer);
//Prinitng the length of vu id.
printf(“PARENT: Length of VU student Id is: %d\n”,(int)(buffer));
printf(“PARENT: Good work child!\n”);
}
return 0;
}
Attachments: