Shell:如何在 shell 脚本中使用屏幕并等待几个后台进程
我正在为几个长时间运行的进程编写 shell 脚本。 首先,我需要运行屏幕会话管理器中的所有命令,以便在用户断开连接时进程的执行不会结束。 后来我需要等待一些之前创建的后台进程结束,以便下面的进程可以启动。
我的问题是如何在 shell 脚本中启动屏幕会话并等待后台进程结束。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Google 上搜索“脚本屏幕”时,第一个结果是此。看起来您可以使用 screen -d -m -S nameOfSession 创建命名屏幕会话。然后
screen -X -S <会话名称> screen
将在 screen 会话“nameOfSession”中创建一个窗口。您可以通过使用与此窗口 1 通信(即为该屏幕会话窗口 1 提供运行命令)。“your_command_here”是您要运行的命令。
^M
是回车控制字符(您在终端中键入 Ctrl-V,然后输入/回车)。 ^M 本质上将“按回车/输入”,以便该命令在此屏幕会话中运行。玩玩它。由于您想等待命令完成,我建议通过&符号分叉进程:
your_command &
紧接着,进程的分叉进程 ID 就在 $! 中。您可以通过运行
wait
等待所有后台进程完成运行。我建议使用屏幕参考。
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
. Thenscreen -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 usingThe "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.
您无法在正在运行的进程上调用
screen
(或nohup
),您必须执行screen script
。但是,您可以执行 nohup 所做的操作,捕获 SIGHUP 并将输出重定向到文件。要等待后台进程,请在创建 pid 时保存它,然后调用 wait
或者只是等待一切完成。
You can't invoke
screen
(ornohup
) on the running process, you have to doscreen script
. You could however do what nohup does, trap SIGHUP and redirect output to a file.To wait for background processes, save the pid when you create it and then call wait
Or alternatively just wait for everything to finish.