Bash pipeline execution

The netcat page mask indicates that in the absence of the -c and -e options, the shell can be serviced via nc using the following commands.

$ rm -f /tmp/f; mkfifo /tmp/f $ cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f 

Now, as I understand it, both reads and writes from fifos block operations. For example, if I run

 $ mkfifo foo $ cat foo 

bash will block because nothing has been written to foo. How does the pipeline in the example from the nc man page not block? I assume that I misunderstand how pipelines run.

+6
source share
2 answers

All commands in the pipeline are executed simultaneously, and not sequentially. That way, cat /tmp/f really blocks, but /bin/sh and nc will still be running until this happens. nc will write to FIFO when the client connects to the port and sends a command, and this will allow cat unlock.

+7
source

The pipe symbol in bash does not matter esle, and then connects the output of the first command to the input of the second. echo "123" | cat echo "123" | cat essentially coincides with cat < <(echo 123) (the latter only launches one subshell, although at first one for each command is launched, but here it can be ignored - plus, this is a bugism and does not work in sh ).

 $ mkfifo foo $ cat foo 

Really blocks - but does not freeze. The moment that any other program writes to foo , cat will display it.

What you do in your call netcat essentially creates cicrle: everything written in FIFO will be displayed on cat , and as cat connected to sh sent last. sh then execute the code (since sh will just execute something written on it, an input stream) and send the output to nc . nc will send it to the client. Everything that the client sends to nc is recorded in FIFO - and our circle is completed.

The mistake you made (I think) is to assume that the second pipe process only reads data once, and not continuously, and therefore must wait for the completion of the first process. This is not true because every process in the pipeline runs in shubshell, so they all work independently of each other.


You should also be able to reorder all the commands in your pipeline. While the former is reading from FIFO, and the latter is writing to him (to complete the lap), he should work.

+3
source

Source: https://habr.com/ru/post/975002/


All Articles