1. 程式人生 > 其它 >shell——程序控制

shell——程序控制

1. 前臺程序後臺程序

前臺程序:執行期間獨佔終端。

1.1 如何避免長耗時程序佔用終端?

如 編譯 kernel 時,將 make 放到後臺,並重定向 標準輸出 標準錯誤

[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[1] 4167

1.2 如何檢視後臺程序執行情況?

[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[1] 4167  # 將一個程序放到後臺後,會顯示 [任務號] 程序號,每個終端有自己的任務號分配。

[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[2] 4849  # 第二個任務

# jobs 檢視後臺程序狀態,
# Done 表示執行成功返回
# Exit 表示錯誤返回
[root@ifw8 polarssl-1.2.17]# jobs
[1]-  Exit                    make > output.txt 2>&1 &
[2]+  Running                 make > output.txt 2>&1 &
  • 表示 fg 命令預設切換的任務
  • 表示 fg 命令切換替補

1.3 如何讓後臺程序 接受 使用者輸入?

後臺程序的標準輸入沒有關聯終端,所以當需要使用者輸入時,會一直阻塞。
為解決這個問題,可以將後臺程序切換為前臺程序。

[root@ifw8 polarssl-1.2.17]# cat &
[1] 6007
[root@ifw8 polarssl-1.2.17]# jobs
[1]+  Stopped                 cat
[root@ifw8 polarssl-1.2.17]# fg %1
cat
adf
adf

若提前知道 程序需要的輸入,可以用 重定向標準輸入 到檔案。避免 使用 fg

1.4 如何將以執行前臺程序 切換到後臺?

用 ctrl-z 讓前臺程序掛起,再用 bg %tid 讓其切換到後臺執行。

[root@ifw8 polarssl-1.2.17]# make 1>./output.txt 2>&1
^Z
[1]+  Stopped                 make > ./output.txt 2>&1
[root@ifw8 polarssl-1.2.17]# jobs
[1]+  Stopped                 make > ./output.txt 2>&1
[root@ifw8 polarssl-1.2.17]# bg %1
[1]+ make > ./output.txt 2>&1 &
[root@ifw8 polarssl-1.2.17]# jobs
[1]+  Running                 make > ./output.txt 2>&1 &

使用 fg %tid ,可以讓 掛起程序 返回前臺繼續執行。

1.5 如何 避免退出終端 導致 後臺程序退出?

預設情況,退出終端,終端的子程序都會被殺死。導致後臺程序被殺死。
使用 nohup 避免這個情況。
nohup 啟動的程序都是後臺程序,當終端退出,nohup 的程序的父程序變成 init 程序。
若沒有重定向標準輸出,預設重定向到 當前目錄下 nohup.out
若沒有重定向標準輸入,預設重定向到 /dev/null

[root@ifw8 polarssl-1.2.17]# nohup make &
[1] 6888
[root@ifw8 polarssl-1.2.17]# nohup: ignoring input and appending output to `nohup.out'

[root@ifw8 polarssl-1.2.17]# ps -aux |grep make
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root      6888  0.0  0.0   4200   884 ?        S    09:36   0:00 make

[root@ifw8 polarssl-1.2.17]# tail -f nohup.out
  Generate      test_suite_gcm.decrypt_128.c
  CC            test_suite_gcm.decrypt_128.c
  Generate      test_suite_gcm.decrypt_192.c

1.6 重要提示

  • 執行後臺程序使用重定向操作時,一定要把後臺執行符號& 放到最後。
  • 使用 fg bg 時,任務號前一定加%
  • 後臺程序隨終端退出而被殺死,應該使用nohup執行後臺程序