Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the PID of a process in a pipeline

Tags:

bash

awk

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_pid #my_prog still has data in its buffer that awk never saw. Data is lost!

In bash, $my_pid points to the PID for awk. However, I need the PID for my_prog. If I kill awk, my_prog does not know to flush it's output buffer and data is lost. So, how would one obtain the PID for my_prog? Note that ps aux|grep my_prog will not work since there may be several my_prog's going.

NOTE: changed cat to awk '...' to help clarify what I need.

like image 214
User1 Avatar asked Jul 27 '10 15:07

User1


People also ask

How do I find the PID number of a process?

Press Ctrl+Shift+Esc on the keyboard. Go to the Processes tab. Right-click the header of the table and select PID in the context menu.

Where is process PID terminal?

You can run ps -A in the terminal to show all the processes (with their process ID) that are currently running.


2 Answers

Just had the same issue. My solution:

process_1 | process_2 &
PID_OF_PROCESS_2=$!
PID_OF_PROCESS_1=`jobs -p`

Just make sure process_1 is the first background process. Otherwise, you need to parse the full output of jobs -l.

like image 151
Marvin Avatar answered Sep 21 '22 03:09

Marvin


I was able to solve it with explicitly naming the pipe using mkfifo.

Step 1: mkfifo capture.

Step 2: Run this script


my_prog > capture &
my_pid="$!" #Now, I have the PID for my_prog!
awk '...' capture > out.csv & 
sleep 10
kill $my_pid #kill my_prog
wait #wait for awk to finish.

I don't like the management of having a mkfifo. Hopefully someone has an easier solution.

like image 25
User1 Avatar answered Sep 21 '22 03:09

User1