Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get process ID of background process?

I start a background process from my shell script, and I would like to kill this process when my script finishes.

How to get the PID of this process from my shell script? As far as I can see variable $! contains the PID of the current script, not the background process.

like image 238
Volodymyr Bezuglyy Avatar asked Dec 15 '09 16:12

Volodymyr Bezuglyy


People also ask

How do you find the PID of a background process?

From help jobs : -l Report the process group ID and working directory of the jobs. jobs -p is another option which shows just the PIDs. To use this in a shell script, you'd have to process the output.

Which command shows the process ID of recent background?

You can use the ps command to find out which processes are running and display information about those processes.

How do I find out what background processes are running?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.


1 Answers

You need to save the PID of the background process at the time you start it:

foo & FOO_PID=$! # do other stuff kill $FOO_PID 

You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.

like image 155
camh Avatar answered Oct 06 '22 14:10

camh