How to get process ID of background process?
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.
You can use the jobs -l
command to get to a particular jobL
^Z
[1]+ Stopped guard
my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18 guard
In this case, 46841 is the PID.
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.
$$
is the current script's pid$!
is the pid of the last background process
Here's a sample transcript from a bash session (%1
refers to the ordinal number of background process as seen from jobs
):
$ echo $$
3748
$ sleep 100 &
[1] 192
$ echo $!
192
$ kill %1
[1]+ Terminated sleep 100