Run python as a daemon process

来源:http://www.cnblogs.com/kungfupanda/archive/2016/05/27/5533258.html
-Advertisement-
Play Games

I am using `&`: why isn't the process running in the background? No problem. We won't show you that ad again. Why didn't you like it? Uninteresting Mi ...


I am using `&`: why isn't the process running in the background?

                
No problem. We won't show you that ad again. Why didn't you like it?
Oops! I didn't mean to do this.
         up vote9down votefavorite 6

I know that I can append & to a command to run the process in the background.

I'm SSH'ing into an Ubuntu 12.04 box and running a python program with $python program.py & -- but when I go to close the terminal window I get a message saying that closing the terminal will kill the running process.

Why is this? I am using the ampersand to run the process in the background. How can I get it to run regardless of if I am SSH'ed in?

    
share|improve this question edited Jun 6 '14 at 23:30          Gilles         342k586121049                 asked Jun 6 '14 at 21:30          bernie2436         1,20252435        
 
                                                                                                                    
Duplicate of unix.stackexchange.com/q/4004/69080                     – Joshua Huber                 Jun 6 '14 at 23:50                                                                            
                                                                                                                    
apt-get install screen, man screen                     – captcha                 Mar 23 at 1:56                                                                                                 
add a comment |                      

5 Answers                                 5

            active                     oldest                     votes
         up vote25down voteaccepted

When you close a terminal window, the terminal emulator sends a SIGHUP to the process it is running, your shell. Your shell then forwards that SIGHUP to everything it's running. On your local system, this is the ssh. The ssh then forwards the SIGHUP to what it's running, the remote shell. So your remote shell then sends a SIGHUP to all its processes, your backgrounded program.

There are 2 ways around this.

  1. Disassociate the backgrounded program from your shell.
    1. Use the disown command after backgrounding your process. This will make the shell forget about it.
    2. Prefix your command with nohup (nohup $python program.py &). This accomplishes the same thing, but by using an intermediate process. Basically it ignores the SIGHUP signal, and then forks & executes your program which inherits the setting, and then exits. Because it forked, the program being launched is not a child of the shell, and the shell doesn't know about it. And unless it installs a signal handler for SIGHUP, it keeps the ignore action anyway.
  2. Use logout instead of closing the terminal window. When you use logout, this isn't a SIGHUP, and so the shell won't send a SIGHUP to any of its children.

Additionally you must make sure that your program doesn't write to the terminal through STDOUT or STDERR, as both of those will no longer exist once the terminal exits. If you don't redirect them to something like /dev/null, the program will still run, but if it tries to write to them, it'll get a SIGPIPE, and the default action of SIGPIPE is to kill the process).

share|improve this answer         answered Jun 6 '14 at 21:58          Patrick         31k674124        
 
4                                                                                  
Technically, ssh dying causes the connection to drop, the connection to drop causes sshd on the other end to die. That sshd controlling the master side of the pseudo-terminal that the remote shell runs, when it dies, that's a hang-up (it's like pulling the plug on a real terminal), so the system sends a SIGHUP to the remote shell.                     – Stéphane Chazelas                 Jun 6 '14 at 22:04                                                                            
                                                                                                                    
@StéphaneChazelas That's one thing I've never dug into. If it's the kernel doing it, how does it determine which process to SIGHUP? It obviously doesn't SIGHUP everything with an open file descriptor to that TTY, as programs will remain running as long as they don't try to use it. So does it pick the program that is currently reading from STDIN (since only one can read from STDIN at a time)?                     – Patrick                 Jun 6 '14 at 22:14                                                                                                 
4                                                                                  
Never mind, answered my own question. POSIX IEEE 1003.1 chap 11, If a modem disconnect is detected by the terminal interface for a controlling terminal ... the SIGHUP signal shall be sent to the controlling process.                     – Patrick                 Jun 6 '14 at 22:24                                                                                                 
1                                                                                  
Also note that nohup generates a nohup.out file with output of the program you start with it. May be annoying to delete that file every time you've used nohup to start an app this way (or you'd need to redirect its output to /dev/null).                     – Ruslan                 Jun 7 '14 at 14:42                                                                            
add a comment |                      
                
No problem. We won't show you that ad again. Why didn't you like it?
Oops! I didn't mean to do this.
         up vote3down vote

The process is running in the background in the terminal, but the output from stdout (and stderr) is still being sent to the terminal. To stop this, add > /dev/null 2>&1 before the & to redirect both the outputs to /dev/null - adding disown also makes sure the process is not killed after you close the terminal:

COMMAND > /dev/null 2>&1 & disown

In your case this would be:

python program.py > /dev/null 2>&1 & disown
share|improve this answer edited Jun 6 '14 at 21:55                 answered Jun 6 '14 at 21:49          Wilf         1,319827        
 
   
add a comment |                      
         up vote1down vote

When you logout, background processes associated with the login session are normally killed as well. If you want them to be disconnected from the session, run them with nohup.

nohup python program.py &
share|improve this answer edited Jun 6 '14 at 21:47          Patrick         31k674124                 answered Jun 6 '14 at 21:37          Barmar         3,791514        
 
   
add a comment |                      
         up vote0down vote

The & operator separates commands to run in parallel, just as ; separates commands to run in series. Both kinds of commands will still run as a child of the shell process.

So, when you close the shell which started those children, the children will be closed also.

What you appear to want is a daemon process, which is significantly more tricky because it needs to dissociate entirely from the parent process. The shell usually doesn't have a simple way of doing that.

share|improve this answer         answered Jun 7 '14 at 3:28          bignose         1586        
 
   
add a comment |                      
         up vote0down vote

After the command ending with ampersand (&), at the command prompt run the command "bg"

bash> python program.py & bash> bg This will put the "&" command to the background bash> jobs This will list the jobs running in the background 

bash> fg 1 This will bring Job #1 to the foreground 

Another way, (to be able to log out)

bash> at now bash> /full/path/python /full/path/program.py bash> ^d   (# That is, Control-D, to run the command, Control-C to cancel) Multiple lines can be submitted to the "at" command, before the ^d (Control-D) see "man at"


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 前言 前幾天看一個朋友的博客時,看他用到了C#6的特性,而6出來這麼長時間還沒有正兒八經看過它,今兒專門看了下新特性,說白了也不過是語法糖而已。但是用起來確實能讓你的代碼更加乾凈些。Let's try it. 1、集合初始化器 public class Post { public DateTime ...
  • 1. JVM相關(包括了各個版本的特性) 對於剛剛接觸Java的人來說,JVM相關的知識不一定需要理解很深,對此裡面的概念有一些簡單的瞭解即可。不過對於一個有著3年以上Java經驗的資深開發者來說,不會JVM幾乎是不可接受的。 JVM作為java運行的基礎,很難相信對於JVM一點都不瞭解的人可以把j ...
  • 需要在程式中使用二維數組,網上找到一種這樣的用法: 1 2 3 4 5 6 #創建一個寬度為3,高度為4的數組 #[[0,0,0], # [0,0,0], # [0,0,0], # [0,0,0]] myList = [[0] * 3] * 4 1 2 3 4 5 6 #創建一個寬度為3,高度為4的 ...
  • 探完閉包[查看],再探命名空間。 對於命名空間,官方文檔已經說得很詳細[查看],我在這裡做了一下實踐和總結。 命名空間一個最明確的目的就是解決重名問題,PHP中不允許兩個函數或者類出現相同的名字,否則會產生一個致命的錯誤。這種情況下只要避免命名重覆就可以解決,最常見的一種做法是約定一個首碼。 例:項 ...
  • 還是從HelloWorld開始說吧... #include <stdio.h> int main(int argc, char* argv[]) { printf("Hello World!\n"); return 0; } 從源文件Hello.cpp編譯鏈接成Hello.exe,需要經歷如下步驟: ...
  • 給初學者之一:淺談java及應用學java 不知不覺也已經三年了 從不知java為何物到現在一個小小的j2ee項目經理雖說不上此道高手,大概也算有點斤兩了吧每次上網,泡bbs逛論壇,沒少去java相關的版面總體感覺初學者多,高手少,精通的更少由於我國高等教育制度教材陳舊,加上java自身發展不過十年 ...
  • 1 二叉樹的鏈式存儲 1.1 鏈式存儲 順序存儲對空間利用率較低,所以,二叉樹一般採用鏈式存儲結構,用一個鏈表來存儲一顆二叉樹。二叉鏈表至少包含3個域:數據域data,左指針域lchild和右指針域rchild,如果再加上一個指向雙親結點的指針就變成了三叉鏈表。 二叉樹的鏈式存儲結構如下: 根據完全 ...
  • C/C++ 預處理元編程 從一個問題開始 以下代碼存在結構性重覆,如何消除? ~~~cpp // EventId.h enum EventId { setupEventId = 0x4001, cfgEventId, recfgEventId, releaseEventId // ... }; ~~ ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...