Search code examples
linuxbashshelldockerinteractive

How to kill interactive shell and process/jobs running on it?


I'm using docker container interactive shell to executed the command on the shell.

e.g. docker exec -i docker_container_name sh

and I launch commands on this interactive shell. Now If I want to kill the this interactive shell and command running on it, How to do that?

I tried sending kill -9 shell_pid or kill -s 15 shell_pid signal to interactive shell. However in this case interactive shell gets killed but the command running on interactive shell is till there and becomes orphan process.

Please let me know how to kill interactive shell with command running on it.


Solution

  • You should get the child(ren) processes first, before killing the shell and kill them too

    CPIDS=`pgrep -P $shellpid` # gets pids of child processes
    kill -9 $shellpid
    for cpid in $CPIDS ; do kill -9 $cpid ; done
    

    Or alternatively (this isn't as safe, because, if running series of commands in shell, next one may be called between those two kill commands)

    pkill -TERM -P $shellpid # sends TERMINATE signal to children
    kill -9 $shellpid