【Linux】守护进程后台训练 & screen命令简介

✨守护进程

如果你通过ssh登录或以ssh为基础的工具软件(比如XShell、PyCharm,VSCode等,可以用这类工具调试,但是最终长时间运行时请以守护进程的方式执行命令)进行远程执行程序时,那么请注意开守护进程来执行程序,避免因为SSH连接中断导致程序终止,遭受不必要的损失。

通过守护进程执行你的程序有多种方式

  1. screen,此外还有常用的tmux(如需安装执行:apt-get update && apt-get install -y tmux)工具,这里不做介绍
  2. jupyterlab的终端
  3. 如果你使用的是Notebook,Notebook断网后日志更新问题请参考JupyterLab文档最下方

✨后台训练

下面介绍通过使用screen命令后台训练

演示环境为macOS(Linux同理)

演示仅为是本机训练,仅为演示screen命令常用操作

实际使用时请先通过ssh连接到服务器再执行以下操作


screen参数介绍

Options:
-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.
-list         or -ls. Do nothing, just list our SockDir.
-L            Turn on output logging.
-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.
-r            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.00.03 (FAU) 23-Oct-06".
-wipe         Do nothing, just clean up SockDir.
-x            Attach to a not detached screen. (Multi display mode).
-X            Execute <cmd> as a screen command in the specified session.

新建会话

screen

创建指定名称会话

screen -S ${SessionName}

列出所有会话

screen -ls


恢复会话

screen -r ${Session}


离开会话

CTRL + A + D 离开会话


终止守护进程

先连接到会话

使用CTRL + C终止进程

然后使用exit终止守护进程


✨screen乱码解决方案

如果使用screen打开终端后中文乱码,执行以下命令后重新进入screen终端:

echo "defencoding GBK" >>  ~/.screenrc
echo "encoding UTF-8 GBK" >>  ~/.screenrc

或者每次使用screen添加-U参数告知Terminal使用UTF-8编码

新建会话

screen -U

恢复会话

screen -U -r ${Session}

✨参考及引用

https://www.autodl.com/docs/daemon/


⭐转载请注明出处

本文作者:双份浓缩馥芮白

原文链接:https://www.cnblogs.com/Flat-White/p/17065037.html

版权所有,如需转载请注明出处。

posted @ 2023-01-23 10:32  双份浓缩馥芮白  阅读(955)  评论(0编辑  收藏  举报