Tony Lin
Tony Lin

Reputation: 805

Python systemd service stops soon after started

I tried to run a Python script as a system service, but the service is not starting. Here is my configuration:

pyntp.service:

[Unit]
Description=Python NTP Service
After=multi-user.target

[Service]
Type=forking
ExecStart=/usr/bin/python $HOME/ntp/ntpservice.py

[Install]
WantedBy=multi-user.target

ntpservice.py:

#!/usr/bin/python

import os
import time
import json

pid = os.fork()

if pid == 0:
    print 'parent'
else:
    print 'child'
    while True:
        print('123')
        time.sleep(1)

The step to start the service is as follows:

cp pyntp.service  /etc/systemd/system/
cp ntpservice.py /usr/local/bin/

systemctl daemon-reload
systemctl enable pyntp.service
systemctl start pyntp.service

The thing is, when I try to see the status of pyntp service, it is always like this:

● pyntp.service - Python NTP Service
   Loaded: loaded (/usr/lib/systemd/system/pyntp.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Wed 2018-11-14 22:27:56 CST; 34min ago
  Process: 801 ExecStart=/usr/bin/python $HOME/ntp/ntpservice.py (code=exited, status=0/SUCCESS)
 Main PID: 801 (code=exited, status=0/SUCCESS)

Nov 14 22:27:56 HES1 systemd[1]: Started Python NTP Service.
Nov 14 22:27:56 HES1 systemd[1]: Starting Python NTP Service...

Can any one help me resolve this? Thanks.

Upvotes: 0

Views: 1281

Answers (1)

Rob Bricheno
Rob Bricheno

Reputation: 4653

Your program is behaving as expected. Just forking isn't enough to make a daemon. What's happening is your code is running as long as its parent process runs, then (both forks are) exiting when the parent process terminates. What you want is to write a daemon (and have that controlled by systemd). You may find this question useful in explaining some easy ways to do that: How do you create a daemon in Python?

fork is an important part of this process but just doing a fork by itself doesn't completely solve the problem. If you'd like to see a more detailed example of how to daemonize your process by hand using fork you can read this: Python code to Daemonize a process?

Upvotes: 1

Related Questions