溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Linux Python守護(hù)進(jìn)程創(chuàng)建與管理

發(fā)布時(shí)間:2024-09-11 21:42:51 來(lái)源:億速云 閱讀:78 作者:小樊 欄目:編程語(yǔ)言

在Linux中,Python守護(hù)進(jìn)程(Daemon)是一種在后臺(tái)運(yùn)行的程序,它不會(huì)占用終端界面

  1. 創(chuàng)建守護(hù)進(jìn)程:

要?jiǎng)?chuàng)建一個(gè)守護(hù)進(jìn)程,你需要導(dǎo)入ossys模塊。以下是一個(gè)簡(jiǎn)單的示例:

import os
import sys

def daemonize():
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError as error:
        print('Unable to fork. Error: %d (%s)' % (error.errno, error.strerror))
        sys.exit(1)

    os.chdir('/')
    os.setsid()
    os.umask(0)

    try:
        pid = os.fork()
        if pid > 0:
            print("Daemon PID %d" % pid)
            sys.exit(0)
    except OSError as error:
        print('Unable to fork. Error: %d (%s)' % (error.errno, error.strerror))
        sys.exit(1)

    return pid

pid = daemonize()

if pid:
    with open("/tmp/daemon_pid.txt", "w") as f:
        f.write("%d" % pid)
else:
    while True:
        # 在這里添加你的守護(hù)進(jìn)程代碼
        pass
  1. 管理守護(hù)進(jìn)程:

要管理守護(hù)進(jìn)程,你可以使用systemdsupervisord等工具。這里我們將介紹如何使用systemd來(lái)管理守護(hù)進(jìn)程。

首先,創(chuàng)建一個(gè)名為your_daemon.servicesystemd服務(wù)文件:

[Unit]
Description=Your Daemon Description
After=network.target

[Service]
User=your_user
Group=your_group
WorkingDirectory=/path/to/your/working/directory
ExecStart=/usr/bin/python3 /path/to/your/daemon/script.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

將此文件放置在/etc/systemd/system/目錄下。然后,運(yùn)行以下命令以重新加載systemd配置并啟動(dòng)守護(hù)進(jìn)程:

sudo systemctl daemon-reload
sudo systemctl start your_daemon.service

要查看守護(hù)進(jìn)程的狀態(tài),請(qǐng)運(yùn)行:

sudo systemctl status your_daemon.service

要停止守護(hù)進(jìn)程,請(qǐng)運(yùn)行:

sudo systemctl stop your_daemon.service

要設(shè)置守護(hù)進(jìn)程在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行,請(qǐng)運(yùn)行:

sudo systemctl enable your_daemon.service

要禁止守護(hù)進(jìn)程在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行,請(qǐng)運(yùn)行:

sudo systemctl disable your_daemon.service

這就是如何在Linux中使用Python創(chuàng)建和管理守護(hù)進(jìn)程。根據(jù)你的需求,你可以根據(jù)實(shí)際情況修改服務(wù)文件和守護(hù)進(jìn)程腳本。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI