Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the below C code to accomodate the following: Let the parent send the dat

ID: 3748032 • Letter: M

Question

Modify the below C code to accomodate the following:

Let the parent send the data to the child through the pipe.

The data sent by the parent should be carrying all the integers in an array declared as shown here: int arr[10]={5,7,9,2,6,3,4,1,7,9} . Note the integers should be copied into the string and then sent.

The child process should sum up all the integers and display the result.

Insert the wait statement in the parent process so it should wait until the child terminates.

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

int main(void)

{

int fd[2], nbytes;

pid_t childpid;

int users = 95;

char mystring[80];

char readbuffer[80];

char digit1,digit2;

digit1 = (char) users%10;

digit2 = (char ) users/10;

mystring[0] = digit1;

mystring[1] = digit2;

printf("%d %d ",mystring[0],mystring[1]);

pipe(fd);

if((childpid = fork()) == -1)

{

perror("fork");

exit(1);

}

if(childpid == 0)

{

/* Child process closes up input side of pipe */

close(fd[0]);

/* Send "string" through the output side of pipe */

write(fd[1], mystring, sizeof(mystring));

exit(0);

}

else

{

/* Parent process closes up output side of pipe */

close(fd[1]);

/* Read in a string from the pipe */

nbytes = read(fd[0], readbuffer, sizeof(readbuffer));

printf("Received string: %d %d ",readbuffer[0],readbuffer[1]);

}

}

Explanation / Answer

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

int main(void)

{

int fd[2], nbytes;

pid_t childpid;

char mystring[80];

char readbuffer[80];

int arr[10]={5,7,9,2,6,3,4,1,7,9};

int i=0, n=0;

for(i=0;i<10;i++)
{
    n = n+sprintf(&mystring[n],"%d",arr[i]);
}

printf("%s ",mystring);

pipe(fd);

if((childpid = fork()) == -1)

{

perror("fork");

exit(1);

}

if(childpid == 0)

{
/* Child process closes up input side of pipe */

close(fd[0]);

/* Send "string" through the output side of pipe */

write(fd[1], mystring, sizeof(mystring));

exit(0);

}

else

{

/* Parent process closes up output side of pipe */

close(fd[1]);

wait(null);

/* Read in a string from the pipe */

nbytes = read(fd[0], readbuffer, sizeof(readbuffer));

printf("Received string: %d %d ",readbuffer[0],readbuffer[1]);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote