Python Daemon Daemon Implementation _python

Source: Internet
Author: User

If you write a service-side program, if CTRL + C exits or closes the terminal, then the server program will quit, so I want to let this program become a daemon, like httpd, has been running on the back end, will not be affected by the terminal.
Daemon English for daemon, like Httpd,mysqld, the last letter D actually means daemon.

Steps for the daemon to write:

1, fork the child process, and then the parent process exits, at which time the child process is taken over by the INIT process.
2, modify the working directory of the child process, create a new process combination session, modify Umask.
3, the child process again fork a process, this process can be called grandson process, and then the child process exits.
4, redirect grandson process standard input stream, standard output stream, standard error to/dev/null
Complete the above 4 steps, then the final grandson process is called Daemon, first look at the code, followed by the reasons for the next step.

 #!/usr/bin/env python #coding =utf8 def createdaemon (): Import OS, sys, time #产生子进程, and then parent
 
  Process Exit Try:pid = Os.fork () if PID > 0:sys.exit (0) except Oserror,error:print ' fork ' sys.exit (1)
    #修改子进程工作目录 Os.chdir ("/") #创建新的会话, the subprocess becomes the first process of the session os.setsid () #修改工作目录的umask os.umask (0) #创建孙子进程, and the child process exits the try: PID = Os.fork () If PID > 0:print "Daemon pid%d"%pid sys.exit (0) except Oserror,error:print "Fork" sys.exit (1) run () def ping (): Import os Os.system (' ping www.baidu.com >/dev/nul ') def Run (): W Hile true:import time,threading fd = open ('/home/ping.log ', ' a ') fd.write ("Start time---------:%s\n"%time.cti Me ()) Fd.flush () t=threading. Thread (target=ping,args= ()) T.start () Time.sleep (3) Fd.write ("End of time--------:%s\n"%time.ctime ()) FD.F Lush () Fd.close () if __name__== ' __main__ ': Createdaemon () 

1, fork child process, the parent process exits
Usually, we execute the service-side program through the terminal to connect to the server, the successful connection will load the shell environment, terminal box shell is a process, the shell process is a terminal process of the child process, through the PS command can be easily viewed, The first program to execute in this shell environment is the child process of the shell process, naturally will be affected by the shell process, in the program after the child process fork, the parent process exit, for the shell process, the parent process even if the execution, and the resulting child process will be taken over by the Init process, So it's out of terminal control.
2. Modify the working directory of the child process
The child process inherits the working directory of the parent process when it is created, and if the program being executed is inside the U disk, it will cause the U disk to not unload.
3. Create a new session
When Setsid is used, the subprocess becomes the first process of a new session, and the subprocess becomes the leader process for the newly-process group, and the child process has no control terminal.
4. Modify Umask
Because Umask will mask permissions, all set to 0, so that you can avoid reading and writing files encountered permissions problems
5.fork grandson process, child process exit
After a few steps, the subprocess becomes the new process group boss, can reapply to open the terminal, in order to avoid this problem, fork grandson process processing,
6. REDIRECT Grandson process standard input stream, standard output stream, standard error flow to/dev/null
Because is the daemon, itself has been out of the terminal, then the standard input stream, standard input stream, standard error stream has no meaning, so all turn to/dev/null, is discarded meaning

We're going to run a program that looks at the effect

From the above figure you can see that this script has been placed in the background, can only use the killall way to end,
Next, we'll look at the logs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.