Writing Linux system daemon instances using Python

Source: Internet
Author: User
A daemon (daemon) is a computer program that executes in the background in UNIX or other multitasking operating systems 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 parent processes (that is, ppid=1) that exist, and is directly under Init at the UNIX system process level. A daemon program usually makes itself a daemon by calling Fork on a child process and then terminating its parent process immediately so that the child process can run under init. – Wikipedia

The daemon differs from the process that is run by the normal user after logging in, it is directly initialized by the system, and the system user is not related, and the user-initiated process is dependent on the terminal connected with the user, when the terminal exits or disconnects, the process will also terminate.
Take a look at the process status of my Linux testing machine:

[Root@home tmp]# ping www.baidu.com >/dev/null &[1] 2759[root@home tmp]# pstree-psystemd (1)-+-agetty (157)      | -agetty (163)      |-avahi-daemon (129)---avahi-daemon (134)      |-AVAHI-DNSCONFD (|-crond)      | | Dbus-daemon (|-haveged)      |-ifplugd (126)      |-nginx (226)---nginx (227)      |-ntpd (223)      | | Python (2727)      |-rngd (124)      |-sshd (216)---sshd (2683)---bash (2690)-+-ping (2759)      |                   '-pstree (2760)      |-systemd (2687)---(sd-pam) (2688)      |-systemd-journal ()      |-systemd-logind (127)      |-systemd-udevd ()      '-wpa_supplicant (153)

As you can see, there is currently a ping program running in the background, if, as disconnected, to log in again, the PING program has been terminated. That is, the ordinary process, and the user session-related, then, how to write a user-session independent, has been running in the background of the process? You may have noticed that python with the PID 2727 above, if just open python normally, it should be run under bash, and here it runs directly under SYSTEMD, in fact, it is a daemon, Take a look at Python's simple implementation of writing the Linux daemon:

#!/usr/bin/env pythonimport osimport signalimport timelogfile= "/tmp/daemon.log" Pid=os.fork () #exit parent Processif Pid:exit () #get the PID of Subprocessdaeid=os.getpid () Os.setsid () os.umask (0) Os.chdir ("/") #Redirection file Descriptorfd=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 (Time.time ())))) 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 the parent process of a process terminates, the system takes over the process and makes Init the parent of the process, and this process becomes a daemon. It is important to note that the Setsid,umask and chdir work directory settings, close file descriptors, set file creation masks, and so on. Save the above code, give permission to run, and open with Python, you will see a new daemon running, and be able to handle the sighup signal sent by the system.

The above procedure is only for testing, can only handle the system SIGHUP signal, 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.