- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这是我正在使用的守护进程
它作为一个基类,我想从另一个 Controller 文件中生成 2 个独立的守护进程
class Daemon:
"""A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
def __init__(self, pidfile,outfile='/tmp/daemon_out',errfile='/tmp/daemon_log'):
self.pidfile = pidfile
self.outfile = outfile
self.errfile = errfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(self.outfile, 'a+')
se = open(self.errfile, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
#method for removing the pidfile before stopping the program
#remove the commented part if you want to delete the output & error file before stopping the program
def delpid(self):
os.remove(self.pidfile)
#os.remove(self.outfile)
#os.remove(self.errfile)
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
#Stop the daemon.
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print (str(err.args))
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop()
self.start()
def run(self):
"""override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
这是我在另一个文件中使用的代码
在这个文件中,我从单独的类扩展守护进程类并覆盖 run() 方法。
#! /usr/bin/python3.6
import sys, time, os, psutil, datetime
from daemon import Daemon
class net(Daemon):
def run(self):
while(True):
print("net daemon : ",os.getpid())
time.sleep(200)
class file(Daemon):
def run(self):
while(True):
print("file daemon : ",os.getpid())
time.sleep(200)
if __name__ == "__main__":
net_daemon = net(pidfile='/tmp/net_pidFile',outfile='/tmp/network_out.log',errfile='/tmp/net_error.log')
file_daemon = file(pidfile='/tmp/file_pidFile',outfile='/tmp/filesys_out.log',errfile='/tmp/file_error.log')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
net_daemon.start()
file_daemon.start()
elif 'stop' == sys.argv[1]:
file_daemon.stop()
net_daemon.stop()
elif 'restart' == sys.argv[1]:
file_daemon.restart()
net_daemon.restart()
else:
print("Unknown command")
sys.exit(2)
sys.exit(0)
else:
print("usage: %s start|stop|restart" % sys.argv[0])
sys.exit(2)
第一个运行 start() 方法的类当前正在运行 &现在只有网络守护进程可以工作,我如何让这 2 个类生成 2 个单独的守护进程??
最佳答案
这里真正的问题是您为所需的任务选择了错误的代码。你在问“我如何使用这把电锯来敲钉子?”在这种情况下,它甚至不是带有说明手册的专业生产的锯,而是您在某人的车库中发现的自制锯,由一个可能知道自己在做什么但您实际上无法确定的人制造,因为你不知道他在做什么。
您提示的最接近的问题是在 daemonize
中:
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
第一次调用时,父进程退出。这意味着父进程永远无法启动第二个守护进程或执行任何其他操作。
对于可以由单独程序管理的自守护程序,这正是您想要的。 (是否把所有的细节都弄对了,我不知道,但基本思路肯定是对的。)
对于产生守护进程的管理程序,这正是您不想要的。这就是你想要写的。所以这是错误的工具。
但任务并没有太大不同。如果你明白你在做什么(并打开你的 Unix Network Programming
副本——没有人能很好地理解这些东西,以至于不会马上想到它),你可以将一个转换成其他。这可能是一个有用的练习,即使对于任何实际应用程序,我只会使用 PyPI 上经过良好测试、文档齐全、维护良好的库之一。
如果您只是将发生在父进程中的 sys.exit(0)
调用(而不是发生在中间子进程中的调用!)替换为 return True< 会发生什么
? (好吧,您可能还想用 return False
替换父级中的 sys.exit(1)
或引发某种异常。)然后 daemonize
不再守护你,而是产生一个守护进程并报告它是否成功。哪个是你想要的,对吧?
不能保证它做的其他所有事情都是正确的(我敢打赌它不会),但它确实解决了您询问的具体问题。
如果在那之后没有明显的错误,下一步可能是通读 PEP 3143 (这很好地将史蒂文斯书中的所有细节翻译成 Python 术语,并确保它们是 21 世纪 linux 和 BSD 的最新版本)并提出要运行的测试 list ,然后运行它们到看看您仍然犯了哪些不太明显的错误。
关于python - 通过两个子类扩展 Daemon 类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49421009/
在前台程序上运行 valgrind 很容易。但是 valgrind 会为守护程序工作并在执行后给出输出。我该怎么做? 谢谢 最佳答案 是的,valgrind 肯定适用于守护程序。 许多守护进程都有某种
网络上有很多守护进程的示例实现。我看到的大多数不使用 daemon(3) 函数在后台运行程序。这只是品味、无知的问题,还是有充分的理由编写我自己的 daemonize 函数?使用 daemon(3)
我使用 apache commons 示例代码编写了一个守护进程: public class LockDaemon implements Daemon { @Override public void
docker出现cannot connect to the docker daemon. is the docker daemon running on this host错误解决办法 发生现象:
我正在使用 Ruby Daemon-kit 设置一个服务,为我的 Rails 应用程序执行各种后台操作。 当我在命令行上调用时它工作正常: ./bin/bgservice 我如何为它创建一个守护进程
当我尝试使用命令'react-native run-android'构建项目时,出现以下错误: 错误:无法找到或加载主类“Dorg.gradle.daemon = true” JS server al
我正在尝试从以下位置安装 memcached:http://blog.elijaa.org/index.php?post/2010/10/15/Memcached-for-Windows&simila
我使用 Xcode 创建了一个命令行工具应用程序。在那个应用程序中,我使用 NSWorkspace 来启动另一个应用程序包 (.app),如此处建议的那样。 MacOsX: How to launch
我正在尝试在一些Ubuntu 14.04流浪者盒子上使用consul设置docker swarm,但是docker守护程序存在问题。我已经在运行progrium / consul容器和swarm ma
我把android studio升级到3.2.0,并创建了默认项目。但是编译器报错: Android resource linking failed Output: D:\android1\proj
首先 - 我知道 UWSGI 建议使用 smart-attach-daemon 来自:http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemo
2018/09/27 我把android studio升级到3.2.0,并创建了默认项目。但是编译器报错: Android resource compilation failed Output: C
错误: Error 1 "bin\Debug\Daemon.exe.manifest;bin\Release\Daemon.exe.manifest" is an invalid value fo
尝试构建 Android 应用程序时出现此错误: > A failure occurred while executing com.android.build.gradle.internal.task
我已经从源码包安装了mysql-5.6.14 尝试开始: vaio1@vaio1-VPCEA3S1E:mysqld 2013-11-17 13:22:18 0 [Warning] Using uni
我知道一些(全部?)守护进程在启动时会 fork 。我的印象是,这是将子进程作为特权较低的用户运行,特别是如果守护进程类似于 HTTP 服务器。 为什么这是必要的?如果不 fork 子进程,进程就不能
我目前正在开发一个守护进程,它将执行很多不同的任务。它是多线程的,并且正在构建以处理几乎任何类型的内部错误而不会崩溃。好吧,我正在处理关闭请求,但我不确定我应该如何去做。 我有一个关闭 Hook 设置
Windows Server的Docker Windows Server 1709版,带有容器 Docker版本17.06.2-ee-6,构建e75fdb8 群集模式(工作程序节点,具有Ubuntu母
使用截至2017年8月25日的最新版本的Docker,我知道Docker不再需要VirtualBox安装程序以及boot2docker才能正常工作。但是,在尝试连接到它并使用docker-compos
是否使用 C 函数 daemon()与使用 fork()、setsid()、umask()、 等显式函数(除了无法设置所有守护进程参数之外)相比,Linux 守护进程在安全性或稳定性方面有任何劣势吗?
我是一名优秀的程序员,十分优秀!