Python スクリプトのデーモン化

トイレのシステムを作っているときに必要があって、検索した結果を記載する。

典拠: https://qiita.com/DQNEO/items/0b5d0bc5d3cf407cb7ff

手順は以下の通り。

①スクリプトを書く。

#!/bin/bash

while true do

echo hello world >> /tmp/hello.log

sleep 1 done

②実行権を与える。

sudo chmod 0755 hello.sh

③Unit 定義ファイルを作る。

sudo nano /etc/systemd/system/hello.service

[Unit]

Description = hello daemon

[Service]

ExecStart = hello.sh

Restart = always

Type = simple

[Install]

WantedBy = multi-user.target

④Unit の認識を確認。

sudo systemctl list-unit-files –type=service | grep hello

⓹enable して、start する。

systemctl enable hello.service

systemctl start hello.service  

⓺python デーモン化の場合は、スクリプトの作法が、python の流儀に則って書いてあり、少し複雑なだけ。

典拠: https://qiita.com/croquisdukke/items/9c5d8933496ba6729c78

/opt/python_daemon.py

#!/usr/bin/env python
import time
import os
import sys

def main_unit():#10秒おきに時刻を書き込む
    while True:
        filepath = ‘/opt/pydmon.log’
        log_file = open(filepath,’a’)
        try:
            log_file.write(time.ctime()+”\n”)
        finally:
            log_file.close()
            time.sleep(10)

def daemonize():
    pid = os.fork()#ここでプロセスをforkする
    if pid > 0:#親プロセスの場合(pidは子プロセスのプロセスID)
        pid_file = open(‘/var/run/python_daemon.pid’,’w’)
        pid_file.write(str(pid)+”\n”)
        pid_file.close()
        sys.exit()
    if pid == 0:#子プロセスの場合
        main_unit()

if __name__ == ‘__main__’:
    while True:
        daemonize()