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

前端 未结 14 1231
无人共我
无人共我 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:31

    Finally, I have managed to find the tail process using ps. Thanks to the idea from ennuikiller.

    I have used the ps to grep tail from the args and kill it. It is kind of a hack but it worked. :)

    If you can find a better way please share.

    Here is the complete script:
    (Latest version can be found here: http://docs.karamatli.com/dotfiles/bin/logserver)

    if [ -z "$1" ]; then
        echo Usage: $0 LOGFILE [PORT]
        exit -1
    fi
    if [ -n "$2" ]; then
        PORT=$2
    else
        PORT=9977
    fi
    
    TAIL_CMD="tail -f $1"
    
    function kill_tail {
        # find and kill the tail process that is detached from the current process
        TAIL_PID=$(/bin/ps -eo pid,args | grep "$TAIL_CMD" | grep -v grep | awk '{ print $1 }')
        kill $TAIL_PID
    }
    trap "kill_tail; exit 0" SIGINT SIGTERM
    
    while true; do
        ( $TAIL_CMD & ) | nc -l -p $PORT -vvv
        kill_tail
    done
    

提交回复
热议问题