Skip to content
Advertisement

Executing bash script via java in background after ssh connection is closed

I am using java to execute a simple bash script on a remote linux machine.

The bash script named “shortoracle.bash” have this script:

#!/bin/sh
runsql() {
   i="$1"
   end=$((SECONDS+360))
   SECONDS=0
   while (( SECONDS < end )); do
   echo "INSERT into table_$i (col1) values (CURRENT_TIMESTAMP);" | sqlplus username/password
   sleep 1
   done
}


for i in $(seq 1 10); do
 echo "DROP TABLE table_$i;" | sqlplus username/password
 echo "CREATE TABLE table_$i (col1 TIMESTAMP WITH TIME ZONE);" | sqlplus username/password
 runsql $i &
done
wait

Simply speaking: create 10 parallel connection that execute queries for 360 seconds.

From my java program i execute the following command:

sshconnection.execute("nohup su - oracle -c './shortoracle.bash'",2000);

The ssh executes the script successfully.

I want,after a timeout of 2 seconds (the second param) to terminate the ssh connection, but for the script to continue to run properly in the background (therefore the nohup, or so i thought), it’s not happening:

After 2 seconds when i terminate the sshconnection, the bash program just stops working:

  • Only 3 of the 10 connections are open.

  • No more inserts happening.

If i give the connection a longer timeout, all is going well, but i don’t want to hangup on this specific connection, i need to move on with the program.

What am i doing wrong here?

Advertisement

Answer

You should add & after your command, i.e.

sshconnection.execute("nohup su - oracle -c './shortoracle.bash' &",2000);

Since nohup itself will otherwise get disconnected when you close the SSH connection. With & you run ‘nohup’ itself in the background and therefore allow it to continue running after you close the SSH connection.

Hope this helps you out!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement