9

My scripts cdist-deploy-to and cdist-mass-deploy (from cdist configuration management) run interactively (i.e. are called by a user).

These scripts call a lot of scripts, which again call some scripts:

cdist-mass-deploy ...
   cdist-deploy-to ...
       cdist-explorer-run-global ...
           cdist-dir ....

What I want is to exit / kill all scripts, as soon as cdist-mass-deploy is either stopped by control C (SIGINT) or killed with SIGTERM.

cdist-deploy-to can also be called interactively and should exhibit the same behaviour.

Using ps -ef... and co variants to find out all processes with the ppid looks like it could be quite unportable. Using $! does not work as in the deeper levels the children are no background processes.

I tried using the following code:

__cdist_kill_on_interrupt()
{
   __cdist_tmp_removal
   kill 0
   exit 1
}

trap __cdist_kill_on_interrupt INT TERM

But this leads to ugly Terminated messages as well as to a segfault in the shells (dash, bash, zsh) and seems not to stop everything instantly anyway:

# cdist-mass-deploy -p ikq04.ethz.ch ikq05.ethz.ch
core: Waiting for cdist-deploy-to jobs to finish
^CTerminated
Terminated
Terminated
Terminated
Segmentation fault

So the question is, how to cleanly exit including all (sub-)children in a portable manner (bourne shell, no csh support needed)?

1
  • 1
    +1. But I am a bit worried about discussing infanticide. Jun 16, 2011 at 23:05

1 Answer 1

2

You don't need to handle ^C, that will result in a signal being sent to the whole process group, which will kill all the processes that are not in the background. So you don't need to catch INT.

The only reason you get a Terminated when you kill them is that kill sends TERM by default, but that's reasonable if you are handling a TERM in the first place. You could use kill -INT 0 if you want to avoid the messages.

(responding with extra info)

If the child processes are run in the background, you can get their process ids just after you start them, using the $! special shell variable. Gather these together in a variable and just kill them all when you need to terminate.

1
  • 1
    Thanks a lot! But, what about the processes that are backgrounded? cdist-mass-deploy starts a lot of cdist-deploy processes, which are backgrounded and waited for using wait.
    – Nico
    Jun 18, 2011 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.