1

I'm aware that similar questions have been asked before on SO (for example here) but I can't get it to work for my case.

I have a bash script called kubetail which evaluates a set of background commands started from the script like this:

CMD="cat <( eval "${command_to_tail}" )"
eval "$CMD"

where command_to_tail calls several subprocesses (kubectl) and aggregates their output into one stream. The problem is that when ctrl+c is pressed during eval it won't interrupt the subprocesses when the main script stops. For example this is shown when I run ps -Af | grep kubectl after I've interrupted the script (the kubectl is spawned by my script):

$ ps -Af | grep kubectl
501 85748 85742   0  9:48AM ttys014    0:00.16 kubectl --context= logs pod-4074277481-3tlx6 core -f --since=10s --namespace=
501 85750 85742   0  9:48AM ttys014    0:00.17 kubectl --context= logs pod-4074277481-9r224 core -f --since=10s --namespace=
501 85752 85742   0  9:48AM ttys014    0:00.16 kubectl --context= logs pod-4074277481-hh9bz core -f --since=10s --namespace=

I've tried various forms of trap - INT but I fail to find a solution that kills all subprocesses on ctrl+c. Any suggestions?

Johan
  • 37,479
  • 32
  • 149
  • 237

1 Answers1

1

The problem you are having is due to all of the subprocesses running independently under there own process ID. When you issue ctrl + c you are attempting to cancel your original script running under its original PID. The subprocesses are unaffected. A simple analogous example is:

#!/bin/bash

declare -i cnt=1
while [ "$cnt" -lt 100 ]; do
    printf "iteration: %2d\n" "$cnt"
    sleep 5
    ((cnt++))
done

When you run the script and then try and cancel the script, control is very likely within the sleep PID and ctrl + c has no effect. If you want control over canceling the script at any point, then you will need to have each subprocess identify that a SIGINT was received by the parent to know an interrupt occurred. In some cases (as with sleep above), that is not directly possible when called from within the script as pressing ctrl + c will not affect the sleep process (which will change on each iteration).

There is no magic-bullet for solving this problem in all cases because what is required will largely depend on what type of control you have over what can be done in the subprocesses and whether your parent script iterates at all that would make a per-iteration check (like for the existence of a temp file) a workable solution.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85