Ssh – Terminate remote process when backgrounded ssh session is terminated

bashremoteshell-scriptingsshterminal

So right now I have a bash script that runs a command on a remote machine using ssh. The machine running the bash script is a Linux machine and the remote machine is a Windows machine running cygwin. The bash script contains the following lines

#!/bin/bash
ssh -i key.pem user@ip "command1" &
# some other commands here, not included because they're not relevant to question
wait

command1 is a long-running process. Currently when I Ctrl-C out of my bash script before wait completes, command1 is still running on the remote machine. It essentially becomes detached and uncontrollable. I want it to terminate when I Ctrl-C, otherwise the remote machine will be littered with many instances of command1 if I constantly terminate my script prematurely. Note the background & is necessary because I want to run other commands while that command is running.

I've tried several methods already

  1. Add the "-t -t" option for pseudo-terminal
  2. Added the below line in the hopes of passing SIGINT to my ssh sessions

    trap 'kill -INT -$$' SIGINT
    

    I also did a variation of the trap command where I got a list of child PIDs and iterated through it killing each one. That didn't work either. SIGHUP also did not work.

So far the only way I've gotten command1 to terminate is if I just run the ssh command

ssh -t -i key.pem user@ip "command1"

without backgrounding it and type Ctrl-C in the same terminal. It doesn't even work if I send a SIGINT or SIGHUP from another terminal.

What is the correct way to terminate remote commands via backgrounded ssh?

NOTE This only happens when the remote machine is a cygwin environment.

Best Answer

Try something like this:

#!/bin/bash
function killcommand1() {
    ssh -i key.pem user@ip 'kill `cat/tmp/command1_pid`'
}

trap "killcommand1" SIGINT

ssh -i key.pem user@ip 'command1 & echo $! > /tmp/command1_pid' &
# other commands
wait

This worked for me going from one Linux system to another, and unfortunately I don't have a cygwin installation available, but this way of sending the kill command could work anyway.