使用 FIFO 时,守护进程内的进程立即退出

问题描述 投票:0回答:1

我的设置大致类似于以下示例:

from contextlib import contextmanager
import subprocess
import os
from pathlib import Path

import daemon


@contextmanager
def tmp_fifo(path: Path):
    try:
        os.mkfifo(path)
        file = os.open(path, os.O_RDWR | os.O_NONBLOCK)
        yield file
    finally:
        os.unlink(path)


with tmp_fifo(Path.home() / "sh.fifo") as fifo, open("dout.log", "w+") as outfile:
    context = daemon.DaemonContext()
    with context:
        with subprocess.Popen(["sh"], stdin=fifo, stdout=outfile) as popen:
            popen.wait()

本质上,我想做的是将 shell 转发到 FIFO。 没有守护进程,这可以工作;即,我可以写

from contextlib import contextmanager
import subprocess
import os
from pathlib import Path


@contextmanager
def tmp_fifo(path: Path):
    try:
        os.mkfifo(path)
        file = os.open(path, os.O_RDWR | os.O_NONBLOCK)
        yield file
    finally:
        os.unlink(path)


with tmp_fifo(Path.home() / "sh.fifo") as fifo, open("dout.log", "w+") as outfile:
    with subprocess.Popen(["sh"], stdin=fifo, stdout=outfile) as popen:
        popen.wait()

它允许我在 FIFO 中输入命令并在日志文件中查看结果。如何使用守护进程重现所需的行为?我尝试将文件重定向到

DaemonContext
构造函数,但这没有帮助。我还查看了配置选项,但似乎没有一个适用。

python mkfifo python-daemon
1个回答
0
投票

您可能需要尝试将 FIFO 和日志文件处理移至守护进程上下文中。尝试如下操作:

from contextlib import contextmanager
import subprocess
import os
from pathlib import Path
import daemon

@contextmanager
def tmp_fifo(path: Path):
    try:
        os.mkfifo(path)
        file = os.open(path, os.O_RDWR | os.O_NONBLOCK)
        yield file
    finally:
        os.unlink(path)

def run_daemonized_shell():
    fifo_path = Path.home() / "sh.fifo"
    log_path = "dout.log"

    # Setup the daemon context FIRST
    with daemon.DaemonContext():
        with tmp_fifo(fifo_path) as fifo:
            with open(log_path, "w+") as outfile:
                with subprocess.Popen(["sh"], stdin=fifo, stdout=outfile) as popen:
                    popen.wait()

if __name__ == "__main__":
    run_daemonized_shell()
© www.soinside.com 2019 - 2024. All rights reserved.