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

Write a C program for Linux called pipes.c that does the following: In the main(

ID: 3846039 • Letter: W

Question

Write a C program for Linux called pipes.c that does the following: In the main() function, it creates a pipe using the pipe() function, then creates two child processes with fork(). Child 1 redirects stdout to the write end of the pipe and then executes with execlp() the "ps -aux" command. Child 2 redirects its input from stdin to the read end of the pipe, then it executes the "sort -r -n -k 5" command. After creating both children, the parent process waits for them to terminate before it can exit. Note that you may have to create Child 2 first, followed by Child 1. The parent program does the same thing as a shell that runs the command "ps -aux | sort -r -n -k 5". You must use the fork(), pipe(), dup2(), close(), execlp() functions (or other exec() variation).

Explanation / Answer

#include #include #include 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) { /* Child process closes up input side of pipe */ close(fd[0]); /* Send "string" through the output side of pipe */ write(fd[1], string, (strlen(string)+1)); 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: %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