Reputation: 51
I'm working on a C minishell project, I'm making |
and <
which copy the behavior of a pipe and an input redirection. The problem is I don't know how could I copy the behavior of this input in bash:
ls | wc -l < myinputfile.txt
Because what it does in bash is to prompt the sum of lines which outputs the first process (ls) and the lines of the **myinputfile.txt ** so firstly ls | wc -l
is 10
and wc -l < myinputfile.txt
is 15
, so the output should be 25
.
For the pipes |
I use the pipe()
function in C and execute both processes each in a child process with fork()
, and if it detects a <
I change the stdin
with dup2(myinputfile, 0)
so in the previous example my output would be 15
and not the sum of both. For execution of the process I need to use execve
so each child process finishes instantly after the execution of the command (if there is no error). How could I prompt the output of the sum of both as in bash in a simple way?
Upvotes: 2
Views: 98
Reputation: 144949
I'm afraid the behavior of ls | wc -l < myinputfile.txt
is not what you explain: the shell opens the file myinputfile.txt for input and redirects the input file to the wc -l
command, replacing the pipe read side that was set up for |
which gets closed.
On one hand, ls
outputs to the pipe (via printf()
, calling write()
), which is closed on the read side, so it gets a SIGPIPE
signal and dies or if it catches this signal, the write
syscall fails with an EPIPE
error, causing the writing process to either exit or continue depending on its error handling at this point.
On the other, wc -l
reads the contents of the file and outputs the number of lines read.
No implicit concatenation occurs.
Conversely, if you write ls & wc -l < myinputfile.txt
, the output of both ls
and wc -l < myinputfile.txt
get mixed in an unpredictable fashion to the current shell output.
To get concatenated output, you could write ls && wc -l < myinputfile.txt
, the output of both ls
and wc -l < myinputfile.txt
get concatenated, assuming ls
exits with a 0
status.
Upvotes: 1