问题
I am writing a shell script for a couple of long running processes. First of all I need to run all commands in the screen session manager, so that the execution of a process does not end if a user has been disconnected. Later I need wait for some background processes, which has been created before, to end, so that the following process can start.
My question is how to start a screen session in a shell script and wait for the background processes to end.
回答1:
You can't invoke screen
(or nohup
) on the running process, you have to do screen script
. You could however do what nohup does, trap SIGHUP and redirect output to a file.
exec > OUT 2>&1
trap '' 1
To wait for background processes, save the pid when you create it and then call wait
foo&
PID1=$!
bar&
PID2=$1
wait $PID1 $PID2
Or alternatively just wait for everything to finish.
foo&
bar&
wait
回答2:
A google search for "scripting screen" gives this as the first result. It looks like you can create named screen sessions with screen -d -m -S nameOfSession
. Then screen -X -S <session name> screen
will create a window in the screen session 'nameOfSession.' You can communicate with this window 1 (i.e. give commands for this screen session window 1 to run) by using
screen -X -S test -p 1 stuff "your command here ^M"
The "your_command_here" is the command you want to run. The ^M
is the carriage return control character (you type Ctrl-V then Enter/Return in a terminal). The ^M will essentially "press return/enter" so that the command is run in this screen session. Play around with it.
Since you want to wait for your commands to finish, I would suggest forking the processes, via the ampersand:
your_command &
Immediately after, the process-id of the forked of process is in $!. You can wait for all background processes to finish running by running wait
.
I would suggest the screen reference.
来源:https://stackoverflow.com/questions/6405039/shell-how-to-use-screen-and-wait-for-a-couple-of-background-processes-in-a-shel