You can read the input with a gets() or fgets() call just before the delay loop in the subprocess section of the code, and then write to the pipe with write().
M. Saad K.
asked 01/25/22Modify the code
Modify the code in such a way that the child process asks for a string from the user.
This string is sent using the pipe to the Parent process and the parent process displays this string.
Code:
#include
#include
#include
#include
#define MSGSIZE 16
char* msg1 = "Hello World #1";
char* msg2 = "Hello World #2";
char* msg3 = "Hello World #3";
int main () {
char inbuf [MSGSIZE];
int p[2], pid, nbytes = 12122121; // p[2] has 2 elements: p[0] and p[1]
if (pipe(p) < 0) // creating a pipe here, with p as the list of IDs
exit(1);
printf("p[0] is =\d\n", p[0]); // ID of the read end
printf("p[0] is =\d\n", p[1]); //ID of the write end
/*continued */
if ((pid = fork ())> 0) {
write (p[1], msg1,MSGSIZE);
write (p[1], msg2,MSGSIZE);
write (p[1], msg3,MSGSIZE);
printf("Parent has written to the Pipe\n\n");
close (p[1]);
wait(NULL);
}
else { //Child Process
close(p[1]);//CHILD only wants to read from the Pipe
while ((nbytes = read (p[0], inbuf, MSGSIZE)) > 0) {
printf ("%s\n, inbuf");
int x; // For Delay only
for (int i=0; i<1000000000; i++){x++;} // For Delay only
printf("nbytes = %d\n",nbytes);
}
printf(nbytes = %d\n,nbytes);
if (nbytes != 0)
exit (2);
printf("Finished reading \n");
}
return 0;
}
1 Expert Answer
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.