In some scenarios where security requirements are high. SSH timeout is pre-set by the administrator, after idle for a period of time SSH connection will be actively disconnected.
This scenario assumes that the script runs through SSH and the script runs longer. Causes the Sshclient and server to time out without interaction for long periods, and the command fails to run.
Using bash subprocess can solve this problem, the idea is that the child process to run detailed logic code, and the main process to monitor the running state of the sub-process, the same time to the console output characters keep alive.
Bash creates a child process in multiple ways. Use "()" here, and then use "&" to run it in the background. Although the process ID of the background process can be obtained through "job-p" and a "wait $PID" method can be used to monitor the return status of the child process, such as the following code. But this is the equivalent of blocking the main process and not running other actions.
For PID in $ (jobs-p); Do wait $piddone
The workaround is to create a new flag file and save the child process return value in another temporary file, and the main process obtains the relevant information through the flag file and the return value. Run the rest of the logic.
Simplified code for example, the main process will print a rotated progress flag while waiting.
function dosomething () { local rettmp=$ (mktemp) local lock= "/tmp/do.lock" Touch $lock ( Real Script to do something echo $?> $retTmp rm-f $lock; ) & While [-f $lock]; do sleep 0.1 printf "Please wait ...%s \ r" $f let "t=10#$ (date +%n)/10000000 0% 4 "case $t in 0) f="/";; 1) f= "-";; 2) f= "\";; 3) f= "|";; Esac done echo local retcode=$ (cat $retTmp) rm-f $retTmp return $retcode}
Such a way is similar to the fork function to implement the relevant logic, feel slightly cumbersome, it is unclear whether Bash has a more convenient way to achieve the master process information synchronization
Prevent long execution of shell scripts resulting in SSH timeouts