Kill process spawned by ssh when ssh dies

I found that simply using -t -t as an argument to ssh made it work. I did not have to set huponexit to either the originating or remote shell.

I tested this as follows:

Doesn't work:

ssh user@remote sleep 100
^C

This killed the ssh session, but I can see the sleep process is still running on the remote host (ps -ef | grep sleep shows it).

Does work:

ssh -t -t user@remote sleep 100
^C

This kills the ssh session and the remote sleep process was also killed. I've also verified that the signal that is sent to the remote process is SIGINT if you use Control-C. I also verified that SIGKILL (-9) applied to the ssh process will also kill the remote process.

EDIT 1:

That was true for sleep ... for more stubborn remote processes, I found that ssh handles ^C differently that SIGINT. Ctrl-C worked, but kill -INT $pid didn'.t

Here is what I finally came up with that worked for my actual application (stealing from the other answers).

ssh -t -t -i id_rsa user@mic0 "/bin/sh -O huponexit -c 'sleep 100'"

Note the nested use of double quotes and single quotes. Note that your remote process MUST respond to SIGHUP by actually exiting!


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.

Tags:

Ssh

Kill