SSH – Kill Process Spawned When SSH Dies

killssh

This is a question that has been addressed several times, not only here, but also in other sites of the stack exchange network (e.g. How to make ssh to kill remote process when I interrupt ssh itself?
). However, I cannot make any of the solutions work for me.

I'm running a command through ssh. Whenever I exit ssh, I want the command to die as well. This command is a daemon called ktserver that runs indefinitely until you press Ctrl-C.

I run it as follows: ssh -t compute-0-1 ktserver and, indeed, when I press Ctrl-C, the process ends gracefully and the ssh session ends.

However, if instead of pressing Ctrl-C, I kill the ssh process using the kill command (for example, sending SIGINT or SIGHUP), the ktserver process stays alive.

How can I make the ktserver always die independent on how ssh is killed?

EDIT: If, instead of ktserver I run something completely different, such as gedit, everything works like a charm (i.e. gedit dies when the connection dies). Therefore, there might be something wrong with the process itself. For example, I thought that it might be ignoring SIGHUP or SIGINT. However, when I run kill -1 ktserver or kill -2 ktserver, the process dies as expected.

EDIT2: As Mark Plotnick points out, the issue is related to the fact that there is no communication circulating on the ssh channel. I've confirmed by running ssh -t <host> read and killing the ssh process afterwards. readwas still alive and kicking.

Best Answer

Usually when ssh connection dies the shell also dies. You can configure your shell to send a signal -1 (SIGHUP) when it terminates to all of its children.

For bash you can configure this option via the builtin command shopt. (shopt -s huponexit).

For zsh you want setoptHUP.

Related Question