I start background process from my shell script.
And I would like to kill this process when my script will be finished.
How to get pid of this process from my shell script?
As far as I can see variable $! contains pid of current script not background process.
views:
171answers:
4
+3
A:
The current script's pid is $$, the pid of the last background process is $!
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
catwalk
2009-12-15 16:28:22
A:
root@berlioz:/tmp# du -s / > x &
root@berlioz:/tmp#
root@berlioz:/tmp# jobs
[1]+ Running du -s / > x &
root@berlioz:/tmp# ps
PID TTY TIME CMD
3238 pts/1 00:00:00 du
3241 pts/1 00:00:00 ps
4562 pts/1 00:57:10 Xvfb
4574 pts/1 00:00:00 dbus-launch
31990 pts/1 00:00:00 su
31998 pts/1 00:00:00 bash
32218 pts/1 00:00:04 metacity
Francis Upton
2009-12-15 16:28:24
+5
A:
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.
camh
2009-12-16 00:05:40