有時候我們運行一個程序,耗時比較長,所以在快下班的時候或是網絡不穩定的時候就比較抓狂。 今天分享幾個我在工作中用到的把程序放在后台運行的方法。
nohup
$ nohup --h Usage: nohup COMMAND [ARG]... or: nohup OPTION Run COMMAND, ignoring hangup signals. --help display this help and exit --version output version information and exit
當運行一個程序的時候,我們在退出當前賬戶,或者關閉終端的時候,程序都會收到一個SIGHUP的信號,nohup就是忽略這種信號,讓程序不掛起。 nohup使用方法很簡單,即:nohup command. 在使用過程中有幾個小技巧:
1. 同時使用nohup和&
使用方法:nohup command &
在退出當前賬戶或是關閉終端的時候程序會收到SIGHUP信號,這個信號會被使用了nohup的程序忽略,但是如果使用了CTRL + C 結束命令,程序會收到SIGINT信號,這個信號還是會讓程序終結,如果不想程序被結束,就在結尾加上一個&, 讓程序也忽略SIGINT 信號
2. 重定向標准輸出和標准錯誤
使用方法: nohup command > filename 2<&1 &
這里的1,2是文件描述符,0表示stdin標准輸入,1表示stdout標准輸出,2表示stderr標准錯誤, 還有一個/dev/null 表示空設備文件。
nohup 默認會把輸出輸出到nohup.out文件中,如果想重定向輸出到別的文件,那么需要在nohup command后加入 > filename, 2<&1,表示把標准錯誤重定向到標准輸出中。
setsid
$ setsid --h Usage: setsid [options] <program> [arguments ...] Run a program in a new session. Options: -c, --ctty set the controlling terminal to the current one -w, --wait wait program to exit, and use the same return -h, --help display this help and exit -V, --version output version information and exit
nohup 通過忽略HUP信號使進程避免中途被中斷,如果我們的進程不屬於接受HUP信號的終端子進程,那么就不會受HUP信號的影響。使用setsid可以幫助我們做到這一點。
使用方法: setsid command