溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Linux中進程在后臺可靠運行的示例分析

發(fā)布時間:2021-07-16 14:33:51 來源:億速云 閱讀:110 作者:小新 欄目:服務器

這篇文章主要介紹Linux中進程在后臺可靠運行的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

場景:

如果只是臨時有一個命令需要長時間運行,什么方法能最簡便的保證它在后臺穩(wěn)定運行呢?

解決方法:

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

hangup 名稱的來由

在 Unix 的早期版本中,每個終端都會通過 modem 和系統(tǒng)通訊。當用戶 logout 時,modem 就會掛斷(hang up)電話。 同理,當 modem 斷開連接時,就會給終端發(fā)送 hangup 信號來通知其關閉所有子進程。

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 即可,標準輸出和標準錯誤缺省會被重定向到 nohup.out 文件中。一般我們可在結尾加上"&"來將命令同時放入后臺運行,也可用">filename 2>&1"來更改缺省的重定向文件名。

nohup 示例

[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 無疑能通過忽略 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 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 ~]#

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

3、這里還有一個關于 subshell 的小技巧。我們知道,將一個或多個命名包含在“()”中就能讓這些命令在子 shell 中運行中,從而擴展出很多有趣的功能,我們現(xiàn)在要討論的就是其中之一。
當我們將"&"也放入“()”內之后,我們就會發(fā)現(xiàn)所提交的作業(yè)并不在作業(yè)列表中,也就是說,是無法通過jobs來查看的。讓我們來看看為什么這樣就能躲過 HUP 信號的影響吧。

subshell 示例

[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 ~]#

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

disown

場景:

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

解決方法:

這時想加 nohup 或者 setsid 已經(jīng)為時已晚,只能通過作業(yè)調度和 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.

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

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

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

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

靈活運用 CTRL-z

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

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

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

CTRL-z 的用途就是將當前進程掛起(Suspend),然后我們就可以用jobs命令來查詢它的作業(yè)號,再用bg jobspec來將它放入后臺并繼續(xù)運行。需要注意的是,如果掛起會影響當前進程的運行結果,請慎用此方法。

disown 示例1(如果提交命令時已經(jīng)用“&”將命令放入后臺運行,則可以直接使用“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

場景:

我們已經(jīng)知道了如何讓進程免受 HUP 信號的影響,但是如果有大量這種命令需要在穩(wěn)定的后臺里運行,如何避免對每條命令都做這樣的操作呢?

解決方法:

此時最方便的方法就是 screen 了。簡單的說,screen 提供了 ANSI/VT100 的終端模擬器,使它能夠在一個真實終端下運行多個全屏的偽終端。screen 的參數(shù)很多,具有很強大的功能,我們在此僅介紹其常用功能以及簡要分析一下為什么使用 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[.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 示例

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

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

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

以上是“Linux中進程在后臺可靠運行的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI