1. 程式人生 > >linux在如何讓程序在後臺執行

linux在如何讓程序在後臺執行

今天碰到這麼一個問題,使用ssh客戶端登陸了linux伺服器,啟動並執行服務之後如果關閉客戶端與伺服器的連線,這個時候運行於伺服器上的服務也會被關閉,如何讓命令提交之後不受本地關閉終端埠的影響呢?

首先我們要知道為啥客戶端的斷開會影響服務端程式的執行?

當用戶登出或者網路斷開時,終端會受到hangup訊號從而關閉其所有的子程序,因此我們要解決的辦法有兩種途徑

  1. 忽略hup訊號。nohup命令
  2. 者讓程序執行在新的會話裡從而成為不屬於此終端的子程序。setsid命令

nohup

nohup可以讓執行的執行緒忽略掉hangup訊號,我們看看nohup的幫組資訊

NAME
       nohup - run a command immune to hangups, with output to a non-tty

SYNOPSIS
       nohup COMMAND [ARG]...
       nohup OPTION

nohup的語法很簡單,只需要在執行的命令之前加上nohup即可。

setsid

如果我們讓執行的執行緒不屬於接受hangup訊號終端的子執行緒,那麼該執行執行緒也不會受終端關閉的影響。通過setsid命令在另外一個session中啟動服務,看看setsid的幫組資訊:

NAME
       setsid - run a program in a new session

SYNOPSIS
       setsid program [arg...]

DESCRIPTION
       setsid runs a program in a new session.

可以看到setsid命令的使用方法同nohup命令同樣簡單,在執行的命令之前加上setsid命令。

有的時候,我們可能忘記了加上命令nohup或者setsid命令,但是在退出終端的時候卻需要服務在後臺執行,有挽救的方法麼? 答案是有的,通過disown命令可以讓啟動的服務在後臺穩定的執行,我們先看看disown的幫助資訊:

 disown [-ar] [-h] [jobspec ...]
              Without options, each jobspec  is  removed  from  the  table  of
              active  jobs.   If jobspec is not present, and neither -a nor -r
              is supplied, the shell鈥檚 notion of the current job is used.   If
              the -h option is given, each jobspec is not removed from the ta-
              ble, but is marked so that SIGHUP is not sent to the job if  the
              shell  receives a SIGHUP.  If no jobspec is present, and neither
              the -a nor the -r option is supplied, the current job  is  used.
              If no jobspec is supplied, the -a option means to remove or mark
              all jobs; the -r option without  a  jobspec  argument  restricts
              operation  to running jobs.  The return value is 0 unless a job-
              spec does not specify a valid job.

-h jobspec:讓某個job忽略掉 hup訊號 -ah:讓所有的job忽略掉hup資訊 -rh:讓正在執行的job忽略掉hup資訊