简体   繁体   中英

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.

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
  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. Solution (2) is ugly, it looks prone to failure.

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. 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. 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. Using PID files is ambiguous due to PID reuse. Only having a supervisor that waits on its children can it properly restart them when they exit or ensure that they are running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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