手机看片精品高清国产日韩,色先锋资源综合网,国产哺乳奶水91在线播放,乱伦小说亚洲色图欧洲电影

Linux中讓進程在后臺運行的方法

2017-04-13 07:53:31 9993

Linux中讓進程在后臺運行的方法


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


$ ./test.sh & 

[1] 17208 


$ jobs -l 

[1]+ 17208 Running ./test.sh & 


對于已經(jīng)在前臺執(zhí)行的命令,也可以重新放到后臺執(zhí)行,首先按ctrl+z暫停已經(jīng)運行的進程,然后使用bg命令將停止的作業(yè)放到后臺運行: 


$ ./test.sh 

[1]+ Stopped ./test.sh 


$ bg %1 

[1]+ ./test.sh & 


$ jobs -l 

[1]+ 22794 Running ./test.sh & 


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


$ echo $$ 

21734 


$ nohup ./test.sh & 

[1] 29016 


$ 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 


$ setsid ./test.sh & 

[1] 409 


$ 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加上&使進程在后臺運行,同時不受當前shell退出的影響。那么對于已經(jīng)在后臺運行的進程,該怎么辦呢?可以使用disown命令: 


$ ./test.sh & 

[1] 2539 


$ jobs -l 

[1]+ 2539 Running ./test.sh & 


$ disown -h %1 


$ 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中執(zhí)行,其實這和setsid異曲同工。方法很簡單,將命令用括號() 括起來即可: 


$ (./test.sh &) 


$ 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 


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


還有一?更加強大的方式是使用screen,首先創(chuàng)建一個斷開模式的虛擬終端,然后用-r選項重新連接這個虛擬終端,在其中執(zhí)行的任何命令,都能達到nohup的效果,這在有多個命令需要在后臺連續(xù)執(zhí)行的時候比較方便: 


$ screen -dmS screen_test 


$ screen -list 

There is a screen on: 

27963.screen_test (Detached) 

1 Socket in /tmp/uscreens/S-jiangfeng. 


$ screen -r screen_test


提交成功!非常感謝您的反饋,我們會繼續(xù)努力做到更好!

這條文檔是否有幫助解決問題?

非常抱歉未能幫助到您。為了給您提供更好的服務(wù),我們很需要您進一步的反饋信息:

在文檔使用中是否遇到以下問題: