我曾经尝试以这种方式运行一项服务,但它是一个稍微大一点的 Python 程序。我退后一步,构建了一个非常简单的 Python 程序,看看能否它运行。当我尝试通过 telnet 连接到此正在运行的套接字时失败。以下是 .socket、.service 和 .py 文件...
testPy.socket
[Unit]
Description=Socket to TESTPY for connection
PartOf=testPy.service
[Socket]
ListenStream=30001
[Install]
WantedBy=sockets.target
testPy.service
[Unit]
Description=TEST PY
After=network.target testPy.socket
Requires=testPy.socket
[Service]
ExecStart=/home/workers/miniconda2/bin/python /home/workers/testPy.py
StandardInput=socket
[Install]
WantedBy=default.target
testPy.py
import sys
END_OF_LINE = '\r\n'
while(1):
input = sys.stdin.readline()
buffer = input.strip()
if not buffer:
sys.stdout.write("OKAY DUDE")
sys.stdout.flush()
continue
if buffer in ['quit', 'QUIT']:
break
sys.stdout.write('\n' + buffer + END_OF_LINE)
sys.stdout.flush()
现在,如果我在命令行中运行它,它运行良好。我可以输入 quit,它就会退出循环,并回显任何内容。
如果我说:
systemctl 启动 testPy.socket
然后输入:
telnet 本地主机 30001
它连接了一点然后就断开了。然后各种状态(对我来说)都不是描述性的:
systemctl status testPy.socket
● testPy.socket - Socket to TESTPY for connection
Loaded: loaded (/etc/systemd/system/testPy.socket; disabled; vendor preset: disabled)
Active: failed (Result: service-failed-permanent) since Thu 2021-03-11 13:59:54 EST; 11min ago
Listen: [::]:30001 (Stream)
Mar 11 13:59:42 dhcp-093.apo.nmsu.edu systemd[1]: Listening on Socket to TESTPY for connection.
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: Unit testPy.socket entered failed state.
systemctl status testPy.service
● testPy.service - TEST PY
Loaded: loaded (/etc/systemd/system/testPy.service; disabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Thu 2021-03-11 13:59:54 EST; 12min ago
Process: 2087 ExecStart=/home/workers/miniconda2/bin/python /home/workers/testPy.py (code=exited, status=1/FAILURE)
Main PID: 2087 (code=exited, status=1/FAILURE)
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: Started TEST PY.
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: testPy.service: main process exited, code=exited, status=1/FAILURE
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: Unit testPy.service entered failed state.
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: testPy.service failed.
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: start request repeated too quickly for testPy.service
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: Failed to start TEST PY.
Mar 11 13:59:54 dhcp-093.apo.nmsu.edu systemd[1]: testPy.service failed.
我相信如果我能让这个简单的测试工作,我就能得到我需要运行的更大的 .py 文件,因为它的工作方式基本相同。我有一个为此构建的服务和套接字,通常有相同的错误。虽然仍然systemctl status kosmos.service
失败,但显示主 PID 状态=0/成功,所以这很奇怪。
它说启动限制是失败,但如果像这里一样简单的服务必须启动、启动、启动,则意味着其他问题,猜测我的套接字或服务文件中的配置,但不确定是什么。我希望我的 python 不会因监听 sys.stdin.readline 等而发生任何变化,并且它读取的行只是来自另一台机器在该端口 (30001) 上建立的连接。我以为这就是所有这些套接字所做的(所有这些都是因为它曾经在带有 xinetd 的旧机器上运行)
答案1
我假设您已经完成了systemctl enable testPy.socket
和systemctl start testPy.socket
步骤?我发现一件事,我还不太明白,那就是testPy.service
不接受作为文件名;systemd 似乎想要[email protected]
。