How to get the PID of a process in a pipeline

前端 未结 9 617
北海茫月
北海茫月 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:36

    I was desperately looking for good solution to get all the PIDs from a pipe job, and one promising approach failed miserably (see previous revisions of this answer).

    So, unfortunately, the best I could come up with is parsing the jobs -l output using GNU awk:

    function last_job_pids {
        if [[ -z "${1}" ]] ; then
            return
        fi
    
        jobs -l | awk '
            /^\[/ { delete pids; pids[$2]=$2; seen=1; next; }
            // { if (seen) { pids[$1]=$1; } }
            END { for (p in pids) print p; }'
    }
    

提交回复
热议问题