ssh连接关闭后,通过Java在后台执行bash脚本 [英] Executing bash script via java in background after ssh connection is closed
问题描述
我正在使用Java在远程Linux机器上执行简单的bash脚本.
I am using java to execute a simple bash script on a remote linux machine.
名为"shortoracle.bash"的bash脚本具有以下脚本:
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
简单来说:创建10个并行连接,执行360秒查询.
Simply speaking: create 10 parallel connection that execute queries for 360 seconds.
在我的Java程序中,我执行以下命令:
From my java program i execute the following command:
sshconnection.execute("nohup su - oracle -c './shortoracle.bash'",2000);
ssh成功执行脚本.
The ssh executes the script successfully.
我想在2秒钟的超时(第二个参数)之后终止ssh连接,但是为了使脚本在后台继续正常运行(因此,nohup或我认为),这没有发生:
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:
在我终止sshconnection的2秒后,bash程序停止工作:
After 2 seconds when i terminate the sshconnection, the bash program just stops working:
-
10个连接中只有3个处于打开状态.
Only 3 of the 10 connections are open.
没有更多的插入发生.
如果我给该连接更长的超时时间,那么一切都很好,但是我不想挂断该特定的连接,我需要继续进行该程序.
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.
我在这里做错什么了?
推荐答案
您应在命令后添加&
,即
sshconnection.execute("nohup su - oracle -c './shortoracle.bash' &",2000);
因为关闭SSH时nohup本身会断开连接
联系.使用&
,您可以在后台运行"nohup"本身,因此,在关闭SSH连接后,它可以继续运行.
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.
希望这对您有所帮助!
这篇关于ssh连接关闭后,通过Java在后台执行bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!