Franko
Franko

Reputation: 131

How to get right PID of a group of background command and kill it?

Ok, just like in this thread, How to get PID of background process?, I know how to get the PID of background process. However, what I need to do countains more than one operation.

{
           sleep 300;

           echo "Still running after 5 min, killing process manualy.";
           COMMAND COMMAND COMMAND

           echo "Shutdown complete"
}&
PID_CHECK_STOP=$!
some stuff...
kill -9 $PID_CHECK_STOP

But it doesn't work. It seems i get either a bad PID or I just can't kill it. I tried to run ps | grep sleep and the pid it gives is always right next to the one i get in PID_CHECK_STOP. Is there a way to make it work? Can i wrap those commands an other way so i can kill them all when i need to?

Thx guys!

Upvotes: 1

Views: 641

Answers (3)

chepner
chepner

Reputation: 531075

kill -9 kills the process before it can do anything else, including signalling its children to exit. Use a gentler signal (kill by itself, which sends a TERM, should be sufficient). You do need to have the process signal its children to exit (if any) explicitly, though, via a trap command.

I'm assuming sleep is a placeholder for the real command. sleep is tricky, however, as it ignores any signals until it returns (i.e., it is non-interruptible). To make your example work, put sleep itself in the background and immediately wait on it. When you kill the "outer" background process, it will interrupt the wait call, which will allow sleep to be killed as well.

{
       trap 'kill $(jobs -p)' EXIT
       sleep 300 & wait

       echo "Still running after 5 min, killing process manualy.";
       COMMAND COMMAND COMMAND

       echo "Shutdown complete"
}&
PID_CHECK_STOP=$!
some stuff...
kill $PID_CHECK_STOP

UPDATE: COMMAND COMMAND COMMAND includes a command that runs via sudo. To kill that process, kill must also be run via sudo. Keep in mind that doing so will run the external kill program, not the shell built-in (there is little difference between the two; the built-in exists to allow you to kill a process when your process quota has been reached).

Upvotes: 2

l0b0
l0b0

Reputation: 58788

The { ... } surrounding the statements starts a new shell, and you get its PID afterwards. sleep and other commands within the block get separate PIDs.

To illustrate, look for your process in ps afux | less - the parent shell process (above the sleep) has the PID you were just given.

Upvotes: 0

perreal
perreal

Reputation: 97948

You can have another script containing those commands and kill that script. If you are dynamically generating code for the block, just write out a script, execute it and kill when you are done.

Upvotes: 1

Related Questions