让你的终端命令跑在后台(关闭终端不影响终端命令执行) |
背景 |
工作中,有时在下班后想执行一些非常耗时的操作(比如拉取某个产品的仓库,或者全编译某个项目的代码),但是公司规定下班后需要关闭个人电脑,那就需要让你的终端命令跑在后台。常见的解决方案有两种,一个是nohup,另一个是screen。下来分别介绍下,使用方法。经过测试推荐使用screen。 |
screen |
screen为多重视窗管理程序。此处所谓的视窗,是指一个全屏幕的文字模式画面。通常只有在使用telnet登入主机或是使用老式的终端机时,才有可能用到screen程序。 |
$ screen --help Use: screen [-opts] [cmd [args]] or: screen -r [host.tty] Options: -4 Resolve hostnames only to IPv4 addresses. -6 Resolve hostnames only to IPv6 addresses. -a Force all capabilities into each window's termcap. -A -[r|R] Adapt all windows to the new display width & height. -c file Read configuration file instead of '.screenrc'. -d (-r) Detach the elsewhere running screen (and reattach here). -dmS name Start as daemon: Screen session in detached mode. -D (-r) Detach and logout remote (and reattach here). -D -RR Do whatever is needed to get a screen session. -e xy Change command characters. -f Flow control on, -fn = off, -fa = auto. -h lines Set the size of the scrollback history buffer. -i Interrupt output sooner when flow control is on. -l Login mode on (update /var/run/utmp), -ln = off. -ls [match] or -list Do nothing, just list our SockDir [on possible matches]. -L Turn on output logging. -Logfile file Set logfile name. -m ignore $STY variable, do create a new screen session. -O Choose optimal output rather than exact vt100 emulation. -p window Preselect the named window if it exists. -q Quiet startup. Exits with non-zero return code if unsuccessful. -Q Commands will send the response to the stdout of the querying process. -r [session] Reattach to a detached screen process. -R Reattach if possible, otherwise start a new session. -s shell Shell to execute rather than $SHELL. -S sockname Name this session <pid>.sockname instead of <pid>.<tty>.<host>. -t title Set title. (window's name). -T term Use term as $TERM for windows, rather than "screen". -U Tell screen to use UTF-8 encoding. -v Print "Screen version 4.06.02 (GNU) 23-Oct-17". -wipe [match] Do nothing, just clean up SockDir [on possible matches]. -x Attach to a not detached screen. (Multi display mode). -X Execute <cmd> as a screen command in the specified session. |
使用命令:screen -dmS screen_name cmd args 开启一个后台窗口执行cmd,cmd支撑携带参数。 命令使用效果如下图: |
![]() |
后台运行的程序可以通过ps查看,缺失已经在运行。也可以通过tail -f 查看输出运行日志输出。 |
通过screen -ls 可以查看通过screen创建的后台窗口。 |
可以通过此窗口ID,可以加载后台窗口到前台。命令使用如下: screen -r "85413.my_test1" 其中“85413.my_test1”为窗口id。 |
![]() |
nohup |
nohup命令实现原理,关闭终端时,会触发SIGHUP信号,通过nohup来忽略这个信号,通过"&"把命令放到后台执行. |
使用方式:nohup <Command> [Arg] & |
执行上述命令后,让命令回到后台,可以通过jobs命令来查看当前放到后台的命令,fg将后台中的命令调至前台继续运行,bg将一个在后台暂停的命令,变成继续执行。 如果后台有多个命令,可以用fg/bg %jobnumber将命令调出,%jobnumber是通过jobs命令查到的后台正在执行的命令的序号。 |
在Ubuntu20.0上测试发现,终端完全关闭后,重新打开的终端无法使用jobs命令来查看放到后台的jobs,但是此命令缺失可以实现把依赖终端的运行的命令放在后台运行。) |
此方法可用于关机时后台编译。但是不是最优。对于在长时间编译后需要进一步交互操作的任务,无法恢复交互界面。所以优先推荐使用screen命令进行。 |
让你的终端命令跑在后台(关闭终端不影响终端命令执行)
于 2022-12-26 21:15:51 首次发布