P.P
P.P

Reputation: 121397

How to kill a process group with kill in bash?

I have a script which is much more complicated but I managed to produce a short script that exhibits the same problem.

I create a process and make it a session leader and then send SIGINT to it. The kill builtin doesn't fail but the process doesn't get killed either (i.e. the default behaviour for SIGINT is to kill). I tried with kill -INT -pid (which should be equivalent to what I do currently) and the /bin/kill command but the behaviour is the same.

The script is as follows:

#!/bin/bash

# Run in a new session so that I don't have to kill the shell
setsid bash -c "sleep 50" &

procs=$(ps --ppid $$ -o pid,pgid,command | grep 'sleep' | head -1)
if [[ -z "$procs" ]]; then
    echo "Couldn't find process group"
    exit 1
fi

PID=$(echo $procs | cut -d ' ' -f 1)
pgid=$(echo $procs | cut -d ' ' -f 2)

if ! kill -n SIGINT $pgid; then
    echo "kill failed"
fi

echo "done"

ps -P $pgid

My expectation is that the last ps command shouldn't report anything (as kill didn't report failure and hence the process should have died) but it does.

I am looking for an explanation of the above noted behaviour and how I can kill a process group (i.e. both the bash and the sleep it starts -- the setsid line above) running in a separate session.

Upvotes: 1

Views: 1269

Answers (1)

gilez
gilez

Reputation: 679

I think you'll find that sleep ignores SIGINT. Take a look at the signals of your sleep command and see. On my Linux box I find:

SigIgn: 0000000000000006

The second bit from the right is set (6 = 4 + 2 + 0), and from the above link: --> 2 = SIGINT Try send a HUP, and you'll find it does kill the sleep.

Upvotes: 2

Related Questions