Linux Tips: Several Ways to Keep Processes Running Reliably in the Background

 

I use: setsid

Usage: setsid command # The command after the command is your normal execution command. For example, run the cs server in the background: setsid ./team 127.0.0.1 test

We often encounter such a problem. We use telnet/ssh to log in to a remote Linux server and run some long-time tasks, but the task fails halfway due to network instability. How can I make the command submit without the interference of closing the terminal window / network disconnection locally? Here are some examples, you can choose different ways to deal with this problem for different scenarios.

nohup/setsid/&

Scenes:

If there is only a temporary command that needs to run for a long time, what is the easiest way to ensure that it runs stably in the background?

Solution:

We know that when the user logs out (logout) or the network is disconnected, the terminal will receive the HUP (hangup) signal to close all its child processes. Therefore, our solution has two ways: either let the process ignore the HUP signal, or let the process run in a new session and become a child process that does not belong to this terminal.

1. nohup

nohup is undoubtedly the first solution we thought of. As the name suggests, the purpose of nohup is to make the submitted command ignore the hangup signal. Let's first look at nohup's help information:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
NOHUP(1)                        User Commands                        NOHUP(1)
 
NAME
        nohup - run a command immune to hangups, with output to a non-tty
 
SYNOPSIS
        nohup COMMAND [ARG]...
        nohup OPTION
 
DESCRIPTION
        Run COMMAND, ignoring hangup signals.
 
        --help display this help and exit
 
        --version
               output version information and exit

It can be seen that the use of nohup is very convenient, just add nohup before the command to be processed, and the standard output and standard error will be redirected to the nohup.out file by default. Generally, we can add "&" at the end to put the command into the background to run at the same time, and it can also be used to change the default redirection file name.">filename 2>&1"

nohup example
1
2
3
4
5
6
7
[root@pvcent107 ~]# nohup ping www.ibm.com &
[1] 3059
nohup: appending output to `nohup.out'
[root@pvcent107 ~]# ps -ef |grep 3059
root      3059   984  0 21:06 pts/3    00:00:00 ping www.ibm.com
root      3067   984  0 21:06 pts/3    00:00:00 grep 3059
[root@pvcent107 ~]#

2。setsid

nohup can undoubtedly prevent our process from being interrupted midway by ignoring the HUP signal, but if we think from another angle, if our process is not a child process of the terminal that accepts the HUP signal, then naturally it will not be affected by the HUP signal. . setsid can help us do that. Let's first look at the help information for setsid:

1
2
3
4
5
6
7
8
9
10
SETSID(8)                 Linux Programmer’s Manual                 SETSID(8)
 
NAME
        setsid - run a program in a new session
 
SYNOPSIS
        setsid program [ arg ... ]
 
DESCRIPTION
        setsid runs a program in a new session.

It can be seen that the use of setsid is also very convenient, and it is only necessary to add setsid before the command to be processed.

setsid example
1
2
3
4
5
[root@pvcent107 ~]# setsid ping www.ibm.com
[root@pvcent107 ~]# ps -ef |grep www.ibm.com
root     31094     1  0 07:28 ?        00:00:00 ping www.ibm.com
root     31102 29217  0 07:29 pts/4    00:00:00 grep www.ibm.com
[root@pvcent107 ~]#

It is worth noting that in the above example, our process ID (PID) is 31094, and its parent ID (PPID) is 1 (that is, the init process ID), not the process ID of the current terminal. Compare this example with the parent ID in the nohup example .

3。&

Here's another little trick about subshells. We know that wrapping one or more names in "()" allows these commands to be run in a subshell, extending a number of interesting features, one of which we're going to discuss now.

When we put "&" into "()", we will find that the submitted job is not in the job list, that is, it cannot jobsbe viewed through. Let's take a look at why this allows us to avoid the influence of the HUP signal.

subshell example
1
2
3
4
5
[root@pvcent107 ~]# (ping www.ibm.com &)
[root@pvcent107 ~]# ps -ef |grep www.ibm.com
root     16270     1  0 14:13 pts/4    00:00:00 ping www.ibm.com
root     16278 15362  0 14:13 pts/4    00:00:00 grep www.ibm.com
[root@pvcent107 ~]#

As can be seen from the above example, the parent ID (PPID) of the newly submitted process is 1 (the PID of the init process), not the process ID of the current terminal. Therefore, it does not belong to the child process of the current terminal, so it will not be affected by the HUP signal of the current terminal.

disown

Scenes:

We already know that the influence of HUP signal can be avoided if nohup or setsid are added before the command. But if we have submitted the command without any processing, how can we remedy it to avoid the influence of the HUP signal?

Solution:

At this time, it is too late to add nohup or setsid, and this problem can only be solved through job scheduling and disown. Let's take a look at the help information for disown:

1
2
3
4
5
6
7
8
9
10
11
disown [-ar] [-h] [jobspec ...]
     Without options, each jobspec is  removed  from  the  table  of
     active  jobs.   If  the -h option is given, each jobspec is not
     removed from the table, but is marked so  that  SIGHUP  is  not
     sent  to the job if the shell receives a SIGHUP.  If no jobspec
     is present, and neither the -a nor the -r option  is  supplied,
     the  current  job  is  used.  If no jobspec is supplied, the -a
     option means to remove or mark all jobs; the -r option  without
     a  jobspec  argument  restricts operation to running jobs.  The
     return value is 0 unless a jobspec does  not  specify  a  valid
     job.

It can be seen that we can achieve our goal in the following ways.

  • Used to make a job ignore the HUP signal.disown -h jobspec
  • disown -ah 来使所有的作业都忽略HUP信号。
  • disown -rh 来使正在运行的作业忽略HUP信号。

需要注意的是,当使用过 disown 之后,会将把目标作业从作业列表中移除,我们将不能再使用jobs来查看它,但是依然能够用ps -ef查找到它。

但是还有一个问题,这种方法的操作对象是作业,如果我们在运行命令时在结尾加了"&"来使它成为一个作业并在后台运行,那么就万事大吉了,我们可以通过jobs命令来得到所有作业的列表。但是如果并没有把当前命令作为作业来运行,如何才能得到它的作业号呢?答案就是用 CTRL-z(按住Ctrl键的同时按住z键)了!

CTRL-z 的用途就是将当前进程挂起(Suspend),然后我们就可以用jobs命令来查询它的作业号,再用bg jobspec来将它放入后台并继续运行。需要注意的是,如果挂起会影响当前进程的运行结果,请慎用此方法。

disown 示例1(如果提交命令时已经用“&”将命令放入后台运行,则可以直接使用“disown”)
1
2
3
4
5
6
7
8
9
[root@pvcent107 build]# cp -r testLargeFile largeFile &
[1] 4825
[root@pvcent107 build]# jobs
[1]+  Running                 cp -i -r testLargeFile largeFile &
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile
root      4825   968  1 09:46 pts/4    00:00:00 cp -i -r testLargeFile largeFile
root      4853   968  0 09:46 pts/4    00:00:00 grep largeFile
[root@pvcent107 build]# logout
disown 示例2(如果提交命令时未使用“&”将命令放入后台运行,可使用 CTRL-z 和“bg”将其放入后台,再使用“disown”)
1
2
3
4
5
6
7
8
9
10
11
12
[root@pvcent107 build]# cp -r testLargeFile largeFile2
 
[1]+  Stopped                 cp -i -r testLargeFile largeFile2
[root@pvcent107 build]# bg %1
[1]+ cp -i -r testLargeFile largeFile2 &
[root@pvcent107 build]# jobs
[1]+  Running                 cp -i -r testLargeFile largeFile2 &
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile2
root      5790  5577  1 10:04 pts/3    00:00:00 cp -i -r testLargeFile largeFile2
root      5824  5577  0 10:05 pts/3    00:00:00 grep largeFile2
[root@pvcent107 build]#

screen

场景:

我们已经知道了如何让进程免受 HUP 信号的影响,但是如果有大量这种命令需要在稳定的后台里运行,如何避免对每条命令都做这样的操作呢?

解决方法:

此时最方便的方法就是 screen 了。简单的说,screen 提供了 ANSI/VT100 的终端模拟器,使它能够在一个真实终端下运行多个全屏的伪终端。screen 的参数很多,具有很强大的功能,我们在此仅介绍其常用功能以及简要分析一下为什么使用 screen 能够避免 HUP 信号的影响。我们先看一下 screen 的帮助信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
SCREEN(1)                                                           SCREEN(1)
 
NAME
        screen - screen manager with VT100/ANSI terminal emulation
 
SYNOPSIS
        screen [ -options ] [ cmd [ args ] ]
        screen -r [[pid.]tty[.host]]
        screen -r sessionowner/[[pid.]tty[.host]]
 
DESCRIPTION
        Screen  is  a  full-screen  window manager that multiplexes a physical
        terminal between several  processes  (typically  interactive  shells).
        Each  virtual  terminal provides the functions of a DEC VT100 terminal
        and, in addition, several control functions from the  ISO  6429  (ECMA
        48,  ANSI  X3.64)  and ISO 2022 standards (e.g. insert/delete line and
        support for multiple character sets).  There is a  scrollback  history
        buffer  for  each virtual terminal and a copy-and-paste mechanism that
        allows moving text regions between windows.

使用 screen 很方便,有以下几个常用选项:

  • screen -dmS session name来建立一个处于断开模式下的会话(并指定其会话名)。
  • screen -list 来列出所有会话。
  • screen -r session name来重新连接指定会话。
  • 用快捷键CTRL-a d 来暂时断开当前会话。
screen 示例
1
2
3
4
5
6
7
[root@pvcent107 ~]# screen -dmS Urumchi
[root@pvcent107 ~]# screen -list
There is a screen on:
         12842.Urumchi   (Detached)
1 Socket in /tmp/screens/S-root.
 
[root@pvcent107 ~]# screen -r Urumchi

当我们用“-r”连接到 screen 会话后,我们就可以在这个伪终端里面为所欲为,再也不用担心 HUP 信号会对我们的进程造成影响,也不用给每个命令前都加上“nohup”或者“setsid”了。这是为什么呢?让我来看一下下面两个例子吧。

1. 未使用 screen 时新进程的进程树
1
2
3
4
5
6
7
8
9
[root@pvcent107 ~]# ping www.google.com &
[1] 9499
[root@pvcent107 ~]# pstree -H 9499
init─┬─Xvnc
      ├─acpid
      ├─atd
      ├─2*[sendmail]
      ├─sshd─┬─sshd───bash───pstree
      │       └─sshd───bash───ping

我们可以看出,未使用 screen 时我们所处的 bash 是 sshd 的子进程,当 ssh 断开连接时,HUP 信号自然会影响到它下面的所有子进程(包括我们新建立的 ping 进程)。

2. 使用了 screen 后新进程的进程树
1
2
3
4
5
6
7
8
9
[root@pvcent107 ~]# screen -r Urumchi
[root@pvcent107 ~]# ping www.ibm.com &
[1] 9488
[root@pvcent107 ~]# pstree -H 9488
init─┬─Xvnc
      ├─acpid
      ├─atd
      ├─screen───bash───ping
      ├─2*[sendmail]

而使用了 screen 后就不同了,此时 bash 是 screen 的子进程,而 screen 是 init(PID为1)的子进程。那么当 ssh 断开连接时,HUP 信号自然不会影响到 screen 下面的子进程了。

总结

现在几种方法已经介绍完毕,我们可以根据不同的场景来选择不同的方案。nohup/setsid 无疑是临时需要时最方便的方法,disown 能帮助我们来事后补救当前已经在运行了的作业,而 screen 则是在大批量操作时不二的选择了。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325100709&siteId=291194637