In some scenarios with high security requirements, the ssh timeout period is preset by the Administrator. After a period of time, the ssh connection is automatically disconnected. In this case, if you execute the script through ssh and the script runs for a long time, it will cause the ssh client and server to time out without interaction for a long time, and the command execution will fail.
Bash sub-processes can solve this problem. The idea is that the sub-process executes specific logic code, and the main process monitors the execution status of sub-processes, and outputs the characters to the console for keep alive.
Bash creates sub-processes in multiple ways. Here "()" is used, and then "&" is used for execution in the background. Although "job-p" can be used to obtain the process ID of the background process and use "wait $ PID" to monitor the return status of the sub-process, the following code is provided. However, this method is equivalent to blocking the main process and cannot execute other actions.
for pid in $(jobs -p); do wait $piddone
The solution is to create a new flag file and save the sub-process return value in another temporary file. The main process obtains relevant information through the flag file and return value, and executes other logic.
The simplified code is as follows. The main process will always print a rotation progress mark 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) / 100000000 % 4" case $t in 0) f="/";; 1) f="-";; 2) f="\\";; 3) f="|";; esac done echo local retcode=$(cat $retTmp) rm -f $retTmp return $retcode}
This method is similar to implementing the relevant logic through the fork function. It feels a little cumbersome. It is unclear whether bash has a simpler way to synchronize information of the main and sub-processes.