Using Python to write Linux system daemon instances _python

Source: Internet
Author: User

A daemon (daemon) is a computer program that executes in the background in a UNIX or other multitasking operating system and does not accept direct manipulation by a computer user. Such programs are initialized in the form of a process. Typically, the daemon does not have any existing parent process (i.e. ppid=1) and is directly under Init at the UNIX system process level. The daemon program usually makes itself a daemon by invoking fork on a child process and then terminating the parent process immediately so that the child process can run under init. – Wikipedia

The daemon distinguishes the process that runs after the normal user logs on to the system, which is initialized directly by the system, has no relationship with the system user, and the user-initiated process is dependent on the user-connected terminal, and the process will terminate as the terminal exits or disconnects.
Take a look at the process status of my Linux test machine:

[Root@home tmp]# ping www.baidu.com >/dev/null &
[1] 2759
[root@home tmp]# pstree-p systemd
(1)-+- Agetty (157)
      |-agetty (163)
      |-avahi-daemon (129)---avahi-daemon (134)
      |-AVAHI-DNSCONFD (a)
      | Crond (121)
      |-dbus-daemon (130)
      |-haveged (128)
      |-ifplugd (126)
      |-nginx (---) nginx (
      MB) | -NTPD (223)
      |-python (2727)
      |-rngd (124)
      |-sshd (216)---sshd (2683)---bash (2690)-+-ping (2759)
      |                   '-pstree (2760)
      |-systemd (2687)---(sd-pam) (2688)
      |-systemd-journal (a)
      |-systemd-logind (127)
      |-systemd-udevd ()
      '-wpa_supplicant (153)

As you can see, there is currently a ping program running in the background, if disconnected, to log in again, the PING program has been terminated. In other words, the common process, and user session-related, then, how to write a user session has nothing to do, has been running in the background of the process? You may have noticed the above PID 2727 python, if it's just a normal turn on Python, it should be running under bash, and here it runs directly under SYSTEMD, in fact, it is a daemon, Take a look at the simple implementation of Python's Linux daemon:

#!/usr/bin/env python
import os
import signal
import time
logfile= "/tmp/daemon.log"
pid= Os.fork ()
#exit parent Process
if Pid:exit ()
#get the PID of subprocess
Daeid=os.getpid (
) Os.setsid ()
os.umask (0)
Os.chdir ("/")
#Redirection file descriptor
fd=open ("/dev/null", "A +")
os.dup2 (Fd.fileno (), 0)
os.dup2 (Fd.fileno (), 1)
os.dup2 (Fd.fileno (), 2) fd.close (
)
log= Open (LogFile, ' a ')
log.write (' Daemon start up at%s\n '% (time.strftime ('%y:%m:%d ', Time.localtime ()))
Log.close ()
def Reload (a,b):
  log=open (logfile, ' a ')
  log.write (' Daemon reload at%s\n '% ( Time.strftime ('%y:%m:%d ', Time.localtime (Time.time ())))
  Log.close () while
True:
  signal.signal ( Signal. Sighup,reload)
  Time.sleep (2)

The point is that with Linux, when a process's parent process terminates, the system takes over the process and lets Init become the parent process of the process, and this process becomes a daemon. It should be noted that the Setsid,umask and chdir work directory settings, closing the file descriptor, setting the file creation mask, and so on. Save the above code, give it permission to run, and open it with Python, you will see a new daemon running and be able to handle the sighup signal sent by the system.

The above program is only for testing and can only handle system SIGHUP signals, please use kill PID to end the process.

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.