Linux讓進程在後台可靠運行的幾種方法

來源:文萃谷 2W

在linux系統下,想讓進程在斷開連接後依然保持運行?如果該進程已經開始運行了該如何補救? 如果有大量這類需求如何簡化操作?

Linux讓進程在後台可靠運行的幾種方法

我們經常會碰到這樣的問題,用 telnet/ssh 登錄了遠程的 Linux 服務器,運行了一些耗時較長的任務, 結果卻由於網絡的不穩定導致任務中途失敗。如何讓命令提交後不受本地關閉終端窗口/網絡斷開連接的干擾呢?

下面舉了一些例子, 您可以針對不同的場景選擇不同的方式來處理這個問題。

  nohup/setsid/&

場景:

如果只是臨時有一個命令需要長時間運行,什麼方法能最簡便的保證它在後台穩定運行呢?

我們知道,當用户註銷(logout)或者網絡斷開時,終端會收到 HUP(hangup)信號從而關閉其所有子進程。因此,我們的解決辦法就有兩種途徑:要麼讓進程忽略 HUP 信號,要麼讓進程運行在新的會話裏從而成為不屬於此終端的子進程。

  1. nohup

nohup 無疑是我們首先想到的辦法。顧名思義,nohup 的用途就是讓提交的命令忽略 hangup 信號。讓我們先來看一下 nohup 的幫助信息。

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

可見,nohup 的使用是十分方便的,只需在要處理的命令前加上 nohup 即可,標準輸出和標準錯誤缺省會被重定向到 文件中。一般我們可在結尾加上"&"來將命令同時放入後台運行,也可用">filename 2>&1"來更改缺省的重定向文件名。

nohup 示例

[root@pvcent107 ~]# nohup ping &

[1] 3059

nohup: appending output to `'

[root@pvcent107 ~]# ps -ef |grep 3059

root 3059 984 0 21:06 pts/3 00:00:00 ping

root 3067 984 0 21:06 pts/3 00:00:00 grep 3059

[root@pvcent107 ~]#

  id

nohup 無疑能通過忽略 HUP 信號來使我們的進程避免中途被中斷,但如果我們換個角度思考,如果我們的進程不屬於接受 HUP 信號的終端的子進程,那麼自然也就不會受到 HUP 信號的影響了。setsid 就能幫助我們做到這一點。讓我們先來看一下 setsid 的幫助信息:

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.

可見 setsid 的使用也是非常方便的,也只需在要處理的命令前加上 setsid 即可。

setsid 示例

[root@pvcent107 ~]# setsid ping

[root@pvcent107 ~]# ps -ef |grep

root 31094 1 0 07:28 ? 00:00:00 ping

root 31102 29217 0 07:29 pts/4 00:00:00 grep

[root@pvcent107 ~]#

值得注意的是,上例中我們的進程 ID(PID)為31094,而它的父 ID(PPID)為1(即為 init 進程 ID),並不是當前終端的進程 ID。請將此例與nohup 例中的父 ID 做比較。

  3.&

這裏還有一個關於 subshell 的小技巧。我們知道,將一個或多個命名包含在“()”中就能讓這些命令在子 shell 中運行中,從而擴展出很多有趣的功能,我們現在要討論的就是其中之一。

當我們將"&"也放入“()”內之後,我們就會發現所提交的作業並不在作業列表中,也就是説,是無法通過jobs來查看的。讓我們來看看為什麼這樣就能躲過 HUP 信號的影響吧。

subshell 示例

[root@pvcent107 ~]# (ping &)

[root@pvcent107 ~]# ps -ef |grep

root 16270 1 0 14:13 pts/4 00:00:00 ping

root 16278 15362 0 14:13 pts/4 00:00:00 grep

[root@pvcent107 ~]#

從上例中可以看出,新提交的進程的父 ID(PPID)為1(init 進程的 PID),並不是當前終端的進程 ID。因此並不屬於當前終端的子進程,從而也就不會受到當前終端的 HUP 信號的影響了。

disown

我們已經知道,如果事先在命令前加上 nohup 或者 setsid 就可以避免 HUP 信號的影響。但是如果我們未加任何處理就已經提交了命令,該如何補救才能讓它避免 HUP 信號的影響呢?

這時想加 nohup 或者 setsid 已經為時已晚,只能通過作業調度和 disown 來解決這個問題了。讓我們來看一下 disown 的幫助信息:

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.

可以看出,我們可以用如下方式來達成我們的目的。

靈活運用 CTRL-z

在我們的日常工作中,我們可以用 CTRL-z 來將當前進程掛起到後台暫停運行,執行一些別的操作,然後再用 fg 來將掛起的進程重新放回前台(也可用 bg 來將掛起的進程放在後台)繼續運行。這樣我們就可以在一個終端內靈活切換運行多個任務,這一點在調試代碼時尤為有用。因為將代碼編輯器掛起到後台再重新放回時,光標定位仍然停留在上次掛起時的位置,避免了重新定位的麻煩。

用disown -h jobspec來使某個作業忽略HUP信號。

用disown -ah 來使所有的作業都忽略HUP信號。

用disown -rh 來使正在運行的作業忽略HUP信號。

需要注意的是,當使用過 disown 之後,會將把目標作業從作業列表中移除,我們將不能再使用jobs來查看它,但是依然能夠用ps -ef查找到它。

但是還有一個問題,這種方法的操作對象是作業,如果我們在運行命令時在結尾加了"&"來使它成為一個作業並在後台運行,那麼就萬事大吉了,我們可以通過jobs命令來得到所有作業的列表。但是如果並沒有把當前命令作為作業來運行,如何才能得到它的作業號呢?答案就是用 CTRL-z(按住Ctrl鍵的同時按住z鍵)了!

CTRL-z 的用途就是將當前進程掛起(Suspend),然後我們就可以用jobs命令來查詢它的'作業號,再用bg jobspec來將它放入後台並繼續運行。

需要注意的是,如果掛起會影響當前進程的運行結果,請慎用此方法。

disown 示例1(如果提交命令時已經用“&”將命令放入後台運行,則可以直接使用“disown”)

[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”)

[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 的幫助信息:

SCREEN(1) SCREEN(1)

NAME

screen - screen manager with VT100/ANSI terminal emulation

SYNOPSIS

screen [ -options ] [ cmd [ args ] ]

screen -r [[pid.]tty[]]

screen -r sessionowner/[[pid.]tty[]]

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 示例

[root@pvcent107 ~]# screen -dmS Urumchi

[root@pvcent107 ~]# screen -list

There is a screen on:

chi (Detached)

1 Socket in /tmp/screens/S-root.

[root@pvcent107 ~]# screen -r Urumchi

當我們用“-r”連接到 screen 會話後,我們就可以在這個偽終端裏面為所欲為,再也不用擔心 HUP 信號會對我們的進程造成影響,也不用給每個命令前都加上“nohup”或者“setsid”了。這是為什麼呢?讓我來看一下下面兩個例子吧。

  1. 未使用 screen 時新進程的進程樹

[root@pvcent107 ~]# ping &

[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 後新進程的進程樹

[root@pvcent107 ~]# screen -r Urumchi

[root@pvcent107 ~]# ping &

[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 下面的子進程了。

熱門標籤