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
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...