Search code examples
pythonlinuxsubprocesspidgnu-screen

Python subprocess.popen wrong pid


I'm trying to write a program that monitors gameservers in Python. For that, n need to look up whether the process of the gameserver, which is started in a screen session is still running, and for that, i need it's pid, however, i don't get the pid of the screen session, i get a pid that only exists till the popen session is active. The pid of the screen session is one pid higher than the pid popen's .pid() method returns. I know that this could be caused through shell=True, but i'm running it with shell=False. Any clean way to get the pid of the screen process/gameserver in the screen process? My only other solution would be just to write .pid()+1, but i guess that would be a horrible workaround.

Here is the relevant part of my code:

proc = Popen(["screen", "-dmS", self.name, "./srcds_run", "-port", str(self.port), "-game", self.modDir], shell=False)

Thanks in advance.


Solution

  • Your problem is not with python, it is with screen.

    When you launch screen with -dmS and it goes into the background it does some forking and execveing by itself, therefore, a new PID, if you use strace to inspect the systemcalls, you will see how the screen binary gets executed in the returned PID that you can see, it later executes other processes and finishes.

    It is the other process you are seeing in your ps calls