How to get the PID of a process that is piped to another process in Bash?

前端 未结 14 1212
无人共我
无人共我 2020-12-01 01:35

I am trying to implement a simple log server in Bash. It should take a file as a parameter and serve it on a port with netcat.

( tail -f $1 & ) | nc -l -         


        
14条回答
  •  再見小時候
    2020-12-01 02:22

    You may store the pid of the tail command in a variable using Bash I/O redirections only (see How to get the PID of a process in a pipeline).

    # terminal window 1
    # using nc on Mac OS X (FreeBSD nc)
    : > /tmp/foo
    PID=$( { { tail -f /tmp/foo 0<&4 & echo $! >&3 ; } 4<&0 | { nc -l 9977 ;} & } 3>&1 | head -1 )
    kill $PID
    
    # terminal window 2
    nc localhost 9977
    
    # terminal window 3
    echo line > /tmp/foo
    

提交回复
热议问题