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

How do you use pipes in C on linux to send information from one child processes

ID: 3597843 • Letter: H

Question

How do you use pipes in C on linux to send information from one child processes to another?

For example:

------------------------------------------------------

C1 = fork();

if(C1 > 0)

{

printf("C1 (PID = %d). Parent: %d ", C1, getppid());

//generates sum of args

int sum=0;

for (i = 1; i < argc; i++)

sum += atoi(argv[i]);

printf("Sum: %d ", sum);

//forks C2

C2 = fork();

if(C2 > 0)

{

printf("C2 (PID = %d). My parent is %d ", C2, getppid());

//calculate the average by passing the sum from C1 to C2 using pipes

//how do you do this?

}

}

Explanation / Answer

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

int main(void)

{

        int     fd[2], nbytes;

        pid_t   childpid;

        char    string[] = "Hello, world! ";

        char    readbuffer[80];

        pipe(fd);

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

        {

                perror("fork");

                exit(1);

        }

        if(childpid == 0)

        {

                close(fd[0]);

                write(fd[1], string, (strlen(string)+1));

                exit(0);

        }

        else

                close(fd[1]);

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

                printf("Received string: %s", readbuffer);

        }     

        return(0);

}

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