问题
I know at least the basics of piping. However, I don't understand how to implement this task in 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:
ls | wc | ./add
Here ls
list the files, wc
gives the counts of the listed files, and ./add
adds the numbers given by wc
.
Please help!
EDIT: It is an assignment. The exact problem statement is given as:
"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..."
回答1:
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.
回答2:
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.
回答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
.
来源:https://stackoverflow.com/questions/12032323/piping-the-output-of-one-command-as-input-to-another-command