1

As discussed in the following StackOverflow question I am creating a Java program that starts a reverse SSH tunnel. I have created a script /root/reverse.sh that starts a subshell and creates a detached ssh reverse session:

#!/bin/bash
( /usr/bin/sshpass -p mypassword ssh -f -N -M -S /tmp/socketuser000.000.000.000 -p 0000 user@000.000.000.000 -R 21022:localhost:22 -R 21080:localhost:80 -o StrictHostKeyChecking=no )

Then this script is executed from java as:

Process process = Runtime.getRuntime().exec("/bin/bash /root/reverse.sh");
int result = process.waitFor();

The connection works just fine, the problem comes when I stop the java program, which is registered as a system service:

systemctl stop myapp

When the java process is killed the reverse ssh connection is killed too. I have checked via pstree that the reverse ssh process parent is PID 1 and not Java.

$ pstree -sg 2185
systemd(1)───ssh(2185)

I don't understand why when I kill the Java process the ssh process is killed too as it's not a child of the Java process. Why does this happen? Has this something to do with process groups? How can I prevent the ssh process from being killed?

1

Your process is getting SIG_HUP or SIG_INT when parent (java) process is exiting.

You may try running it with nohup so it will ignore SIG_HUP signal. Also you may include:

trap 'echo "Got sigint"' INT

in your .sh file, so instead of exiting normal way it would handle SIG_INT by echoing text. Feel free to use any other function to handle signals.

Also there is very good answer about signals here: What causes various signals to be sent?

Please consider changing your approach to this problem as this looks like a bad design pattern when you expect service to do something and keep doing it when service is stopped.

3
  • Hello, thanks for your response. I have tried changing the script execution command to nohup /bin/bash /root/reverse.sh and I have also changed the ssh command inside the script to nohup /usr/bin/sshpass -p mypassword ssh -f -N -M -S /tmp/socketuser000.000.000.000 -p 0000 user@000.000.000.000 -R 21022:localhost:22 -R 21080:localhost:80 -o StrictHostKeyChecking=no. Unfortunately I am getting the same behaviour where the SSH connection is closed when the service is stopped.
    – PauMAVA
    Mar 29 at 10:39
  • I have also tried adding & disown at the end of the commands as described here unix.stackexchange.com/questions/421539/… which also didn't work.
    – PauMAVA
    Mar 29 at 10:48
  • @PauMAVA: Updated my answer according to your description.
    – DevilaN
    Mar 31 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.