1

I am killing multiple processes using "kill -9 pid" in a shell script and as expected the exit code is nonzero.

Is there any way to get exit code 0 while also killing the process using its pid?

Code snippet:

echo $1 $2
for pid in $(ps -ef | grep "$1" | grep "$2" | grep "main-app" | grep -v grep | awk '{print $2}'); do
    kill -9 $pid 
    exit 0
done
2
  • 1
    Why do you want that? This sounds like an XY Problem Commented Dec 8, 2021 at 11:22
  • 1
    If you want a process to respond to a signal by exiting 0, then that process will need to handle the signal. Since SIGKILL cannot be caught, you won't be able to do that with kill -9. Clean up the receiving process so it handles SIGTERM and stop smashing it with a sledge hammer. Commented Dec 8, 2021 at 12:08

2 Answers 2

1

In the general case, the exit code when a process is killed is unpredictable.

Bash takes care to set the exit code of a killed process to 128 + the signal it was killed by, so kill -9 will always cause Bash to report exit code 137.

With kill -9 in particular, the receiving process has absolutely no control over its exit code; it is simply killed immediately.

It is quite hard to argue that there would be any circumstances where a process should report success when it is forcibly interrupted, anyway. Though of course, if you have control over the source code of the process, you can make it explicitly exit 0 on some signals (though again, not for kill -9 which cannot be handled).

Aside: You should basically never use kill -9. It is an emergency stop which should only be utilized in unusual situations (and even then you should know what you are doing).

As a further aside, you want to remove the useless greps you have there.

for pid in $(ps -ef |
    awk -v first="$1" -v second="$2" -v app="main-app" '
        $0 ~ first && $0 ~ second && $0 ~ app && !/awk/ {print $2}')
do
    kill "$pid"
done

The exit 0 you had in there would terminate the current shell (and of course, exit the loop).

Incidentally, the linked page also has a section about why to avoid kill -9.

Sign up to request clarification or add additional context in comments.

Comments

0

The following simple one-line solution works fine with all kinds of Linux/Unix. I tested it with Ubuntu, Mint, Centos, Amazon Linux, and Alpine (Docker).

This runs in a new shell and this way you can control properly the exit code.

/bin/bash -c '/usr/bin/killall -q <process-name>; exit 0'

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.