如何讓進程在Linux後台運行

來源:互聯網
上載者:User

在Linux中,如果要讓進程在後台運行,一般情況下,我們在命令後面加上&即可,實際上,這樣是將命令放入到一個作業隊列中了:

[root@localhost /]# ./test.sh &

[1] 17208

然後我們就可以用以下命令進行查看:

[root@localhost /]# jobs -l

[1]  17208 Running ./test.sh &

對於已經在前台執行的命令,也可以重新放到後台執行首先按ctrl z暫停已經啟動並執行進程,然後使用bg命令將停止的作業放到後台運行:

[root@localhost /]# bg %1

[1]  ./test.sh &

[root@localhost /]# jobs -l

[1]  22794 Running ./test.sh &

但是如上方到後台執行的進程,其父進程還是當前終端shell的進程,而一旦父進程退出,則會發送hangup訊號給所有子進程,子進程收到hangup以後也會退出。如果我們要在退出shell的時候繼續運行進程,則需要使用nohup忽略hangup訊號,或者setsid將將父進程設為init進程(進程號為1)

[root@localhost /]# echo $$
21734

[root@localhost /]# nohup ./test.sh &amp;<br />
[1] 29016

[root@localhost /]# ps -ef | grep test
515 29710 21734 0 11:47 pts/12 00:00:00 /bin/sh ./test.sh
515 29713 21734 0 11:47 pts/12 00:00:00 grep test

[root@localhost /]# setsid ./test.sh &
[1] 409

[root@localhost /]# ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 413 21734 0 11:49 pts/12 00:00:00 grep test

上面的實驗示範了使用nohup/setsid加上&amp;使進程在後台運行,同時不受當前shell退出的影響。那麼對於已經在後台啟動並執行進程,該怎麼辦呢?可以使用disown命令:

[root@localhost /]# ./test.sh &
[1] 2539

[root@localhost /]# jobs -l
[1]  2539 Running ./test.sh &

[root@localhost /]# disown -h %1

[root@localhost /]# ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 2542 21734 0 11:52 pts/12 00:00:00 grep test

另外還有一種方法,即使將進程在一個subshell中執行,其實這和setsid異曲同工。方法很簡單,將命令用括弧() 括起來即可:

[root@localhost /]# (./test.sh &)

[root@localhost /]# ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 12483 21734 0 11:59 pts/12 00:00:00 grep test

註:本文實驗環境為Red Hat Enterprise Linux AS release 4 (Nahant Update 5),shell為/bin/bash,不同的OS和shell可能命令有些不一樣。例如AIX的ksh,沒有disown,但是可以使用nohup -p PID來獲得disown同樣的效果。

還有一種更加強大的方式是使用screen,首先建立一個斷開模式的虛擬終端,然後用-r選項重新串連這個虛擬終端,在其中執行的任何命令,都能達到nohup的效果,這在有多個命令需要在後台連續執行的時候比較方便:

[root@localhost /]# screen -dmS screen_test

[root@localhost /]# screen -list
There is a screen on:
27963.screen_test (Detached)
1 Socket in /tmp/uscreens/S-jiangfeng.

[root@localhost /]# screen -r screen_test

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.