When attempting to establish an ssh tunnel, I noticed that even if the connection fails, the process stays alive. For example, if I try to run this command while
hostname is down:
/usr/bin/ssh -f -i /home/user/.ssh/id_rsa -N -R 3000:localhost:22 user@hostname
Occasionally I get the response:
Warning: remote port forwarding failed for listen port 3000
I only get this error message when the original process (running on the local machine) dies but the remote server does not realize yet. The process tries to restart but the server thinks it still has a connection on 3000 and won't except a new connection, resulting in the warning above.
But if I do a
pgrep -x ssh I can see that the process is still alive. I would like to run this ssh command as part of a bash script in a cronjob which first checks to see if the tunnel is established and if not reestablishes it, but the way I have the script setup it either a) sees that the tunnel is down and attempts to create a new one (which secretly fails), or b) sees that the failed process is alive and does nothing. The result is that the tunnel never gets reestablished so long as that failed process still exists.
Is there a way to just kill the process if the connection fails instead of getting a warning?