'Piping the output of one command as input to another command [closed]
I have the following assignment:
Write a C program to read the names of two (or more) executable programs, and redirect the output of the first program to the input of the second program, output of the second program to the input of the third program, and so on...
I know at least the basics of piping in a shell. However, I don't understand how to implement this task in C using C pipes. I don't know how to take the output of one program as an input to another program and so on. Eg, in a shell:
ls | wc | ./add
Here ls list the files, wc gives the counts of the listed files, and ./add adds the numbers given by wc.
Where do I start implementing piping in a C program?
Solution 1:[1]
It appears that you need to create a program that does a simple case of the shell's job: creates and executes a pipeline of commands then outputs the result.
To do this right requires you to understand SIGPIPE, child process handling, input/output redirection, file descriptors, fork() and exec(), wait(), and more.
This Linux Documentation Project article on creating pipelines should help set you on the right path.
Solution 2:[2]
When you use pipe(pipefd) to create a pipe, you get two file descriptors. Whatever is written to pipefd[1] can be read from pipefd[0]. So what you have to do is execute the first program such that its stdout is the same as pipefd[1], and execute the second program such that its stdin is the same as pipefd[0]. You use the dup()/close() trick to renumber the file descriptors just before executing the commands so that they become 0 (stdin) or 1 (stdout).
For piping together three programs, you will have two pipes. The middle program will be reading from the first one and writing to the second one.
Solution 3:[3]
The shell handles all the grunt work with setting up the pipes and creating processes, so you don't have to worry about that at all. From your programs point of view, this is normal input from stdin, which means you can use the normal input function such as scanf or fread from stdin.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gabriel Staples |
| Solution 3 | Some programmer dude |
