Linux --- 程序後臺運行的幾種方法

有時候咱們運行一個程序,耗時比較長,因此在快下班的時候或是網絡不穩定的時候就比較抓狂。 今天分享幾個我在工做中用到的把程序放在後臺運行的方法。bash

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 &session

在退出當前帳戶或是關閉終端的時候程序會收到SIGHUP信號,這個信號會被使用了nohup的程序忽略,可是若是使用了CTRL + C 結束命令,程序會收到SIGINT信號,這個信號仍是會讓程序終結,若是不想程序被結束,就在結尾加上一個&, 讓程序也忽略SIGINT 信號this

2. 重定向標準輸出和標準錯誤

使用方法: nohup command > filename 2<&1 &orm

這裏的1,2是文件描述符,0表示stdin標準輸入,1表示stdout標準輸出,2表示stderr標準錯誤, 還有一個/dev/null 表示空設備文件。blog

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能夠幫助咱們作到這一點。terminal

使用方法: setsid command it

相關文章
相關標籤/搜索