简体   繁体   English

在python中创建进程,仅当它不存在时

[英]Create process in python, only if it doesn't exist

I have a python server that eventually needs a background process to perform an action.我有一个 python 服务器,它最终需要一个后台进程来执行一个操作。

It creates a child process that should be able to last more than its parent.它创建的子进程应该能够比其父进程持续更长时间。 But it shouldn't create such a child process if it is already running (it can happen if a previous parent process created it).但是,如果它已经在运行,则不应创建这样的子进程(如果先前的父进程创建了它,则可能会发生这种情况)。

I can think of a couple of different aproaches to solve this problem:我可以想到几种不同的方法来解决这个问题:

  1. Check all current running processes before creating the new one: Cross-platform way to get PIDs by process name in python在创建新进程之前检查所有当前正在运行的进程: Cross-platform way to get PIDs by process name in python
  2. Write a file when the child process starts, delete it when it's done.在子进程启动时写入一个文件,完成后将其删除。 Check the file before creating a child process.在创建子进程之前检查文件。

But none of them seem to perfectly fit my needs.但它们似乎都不能完全满足我的需求。 Solution (1) doesn't work well if child process is a fork of its parent.如果子进程是其父进程的分支,则解决方案 (1) 无法正常工作。 Solution (2) is ugly, it looks prone to failure.解决方案 (2) 很丑陋,看起来很容易失败。

It would be great for me to provide a fixed pid or name at process creation, so I could always look for the process in system in a fixed way and be certain if it is running or not.在进程创建时提供固定的 pid 或名称对我来说非常好,这样我就可以始终以固定方式在系统中查找进程并确定它是否正在运行。 But I haven't found a way to do this.但我还没有找到办法做到这一点。

"It creates a child process that should be able to last more than its parent." “它创建了一个子进程,它应该能够比其父进程持续更长时间。” Don't.别。

Have a longer lived service process create the child for you.让一个更长寿的服务过程为您创造孩子。 Talk to this service over a Unix domain socket.通过 Unix 域套接字与此服务对话。 It then can be used to pass file descriptors to the child.然后它可用于将文件描述符传递给子进程。 The service can also trivially ensure that it only ever has a single child.该服务还可以轻松确保它只有一个孩子。

This is the pattern that can be used to eliminate the need for children that outlive their parents.这种模式可用于消除对比父母寿命长的孩子的需求。

Using command names makes it trivial to do a DoS by just creating a process with the same name that does nothing.使用命令名称只需创建一个不执行任何操作的同名进程即可轻松执行 DoS。 Using PID files is ambiguous due to PID reuse.由于 PID 重用,使用 PID 文件是不明确的。 Only having a supervisor that waits on its children can it properly restart them when they exit or ensure that they are running.只有拥有一个等待其子项的主管才能在它们退出时正确地重新启动它们或确保它们正在运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM