Python development [note]: add the python program to the systemctl System Service, pythonsystemctl
Systemctl System Service
Environment: centos7
Details about how to use the systemctl Service
Implementation
Normally, we create a file with the. service suffix under the/usr/lib/systemd/system/directory, such as cdr. service.
[Unit]Description=cdrAfter=network.target[Service]ExecStart=/opt/pbx/cdr/cdr.pyType=forking[Install]WantedBy=multi-user.target
Usage:
# Start systemctl start cdr # disable systemctl stop cdr # view status systemctl status cdr # enable auto-start systemctl enable cdr # disable enable auto-start systemctl enable cdr
Normal python programs can be used in this way, but in this case, it is difficult to use the above. servcie file creation method, as shown below:
#!/usr/bin/env python# -*- coding:utf-8 -*-import loggingimport timeimport syslogging.basicConfig(level=logging.INFO)def daemon(): import os # create - fork 1 try: pid = os.fork() if pid > 0: return pid except OSError as error: logging.error('fork #1 failed: %d (%s)' % (error.errno, error.strerror)) return -1 # it separates the son from the father os.chdir('/opt/pbx') os.setsid() os.umask(0) # create - fork 2 try: pid = os.fork() if pid > 0: return pid except OSError as error: logging.error('fork #2 failed: %d (%s)' % (error.errno, error.strerror)) return -1 sys.stdout.flush() sys.stderr.flush() si = open("/dev/null", 'r') so = open("/dev/null", 'a+') se = open("/dev/null", 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) return 0def main(): pid = daemon() if pid: return pid while True: logging.info('----------') time.sleep(1)main()
The biggest difference this time is that a sub-process is fork in the python program. In this case, the first method is difficult. After multiple tests, we found that the following method can achieve our results.
[Unit]Description=lzlAfter=network.target[Service]Type=oneshotRemainAfterExit=yesExecStart=/usr/bin/python3 /home/lzl/workspace/cdrservice/main.py[Install]WantedBy=multi-user.target