3

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.

NublicPablo
  • 959
  • 11
  • 21
  • Maybe investigate if python's daemon lib can be of help here: https://www.python.org/dev/peps/pep-3143/#example-usage – Jarek.D Feb 19 '19 at 11:15

1 Answers1

2

"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.

Dan D.
  • 73,243
  • 15
  • 104
  • 123