How to get the PID of a process in a pipeline

前端 未结 9 564
北海茫月
北海茫月 2020-12-03 01:51

Consider the following simplified example:


my_prog|awk \'...\' > output.csv &
my_pid=\"$!\" #Gives the PID for awk instead of for my_prog
sleep 10
kill $my         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 02:32

    Add a shell wrapper around your command and capture the pid. For my example I use iostat.

    #!/bin/sh
    echo $$ > /tmp/my.pid
    exec iostat 1
    

    Exec replaces the shell with the new process preserving the pid.

    test.sh | grep avg
    

    While that runs:

    $ cat my.pid 
    22754
    $ ps -ef | grep iostat
    userid  22754  4058  0 12:33 pts/12   00:00:00 iostat 1
    

    So you can:

    sleep 10
    kill `cat my.pid`
    

    Is that more elegant?

提交回复
热议问题