Linux 后台执行任务,tmux session 操作指南

前言

用ssh执行命令,如果遇到网络中断,就不能完成执行,因为会直接中断。但是我们有时候,又需要在后台一直跑一些任务,不希望它被中断。

好在万能的Linux,不会让我们失望。

我们可以通过tmux来执行session,然后执行命令,这样会在后台执行,而不会被中断

先确保系统安装了tmux

登录ssh之后,先检查下系统有没有装tmux, 如果没有装,用root权限 装一下

# debian/ubuntu
sudo apt-get install -y tmux
# centos/fedora
sudo yum install -y tmux

利用tmux session来在后台执行任务

先看看手册是怎么说的


 

 new-session [-AdDEP] [-c start-directory] [-F format] [-n window-name] [-s session-name] [-t group-name] [-x width] [-y height] [shell-command]
 (alias: new)
 Create a new session with name session-name.
 The new session is attached to the current terminal unless -d is given. window-name and shell-command are the name of and shell command to execute in the
 initial window. With -d, the initial size comes from the global default-size option; -x and -y can be used to specify a different size. ¡®-¡¯ uses the size
 of the current client if any. If -x or -y is given, the default-size option is set for the session.
 If run from a terminal, any termios(4) special characters are saved and used for new windows in the new session.
 The -A flag makes new-session behave like attach-session if session-name already exists; in this case, -D behaves like -d to attach-session.
 If -t is given, it specifies a session group. Sessions in the same group share the same set of windows - new windows are linked to all sessions in the group
 and any windows closed removed from all sessions. The current and previous window and any session options remain independent and any session in a group may
 be killed without affecting the others. The group-name argument may be:
 1. the name of an existing group, in which case the new session is added to that group;
 2. the name of an existing session - the new session is added to the same group as that session, creating a new group if necessary;
 3. the name for a new group containing only the new session.
 -n and shell-command are invalid if -t is used.
 The -P option prints information about the new session after it has been created. By default, it uses the format ¡®#{session_name}:¡¯ but a different format
 may be specified with -F.
 If -E is used, the update-environment option will not be applied.

原文我就不翻译了,下面演示怎么操作。

首先我们编写一个shell脚本,内容是你想执行的任务。比如位于/opt/my_script.sh

然后登陆 服务器的ssh控制台,执行命令,开启一个tmux 新的session

tmux new-session -d -s "myTempSession" /opt/my_script.sh

-d 参数表示这个session,会在后台执行

-s 是这个session的名字,你可以随便取个名字

后面,如果你要看执行结果,可以执行 tmux attach-session -t myTempSession.

就可以进入session(会话)查看执行的结果和进展。

如果你后悔了,或者任何时间,不想要看什么结果,你可以杀掉这个tmux session

tmux kill-session -t targetSession

意思是我不需要看什么结果,直接干掉它就行了

总结

现在,你学会了如何让linux在后台,帮你执行一个不会被随意终止的shell脚本。可以完成很多有意义的事情。比如完成科学计算,通过ssh下载一个巨大的视频文件。

希望能帮助到大家。有问题,欢迎反馈。

分类: Linux/Unix 标签: 发布于: 2020-12-26 16:34:55, 点击数: