1

According to Python 3.6 docs for Popen:

If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only)

Then why does the parent process hang while the preexec_fn function is executed? If it is executed in the child process then the parent should be able to proceed.

Here is a small example of a program that creates a new "ls" process before which it sleeps for 4 seconds. Ideally "reached" should be printed immediately but that is not the case. "reached" in printed 4 seconds later.

import os
import subprocess
import sys
import tempfile
import time


def sleep_a_little():
    time.sleep(4)


p = subprocess.Popen(["ls"], preexec_fn=sleep_a_little)
print("reached")
Ayush Ranjan
  • 59
  • 12
  • Probably [this](https://stackoverflow.com/questions/39477003/python-subprocess-popen-hanging) – Matt May 03 '20 at 08:02
  • Hmm @Matt, it doesn't look like it because Popen is not hanging forever. The linked answer talks about a potential deadlock. It is hanging for 4 seconds since the `preexec_fn` takes 4 seconds to execute. My question is that the parent process should not be waiting on the preexec_fn to execute because that happens in the child process. – Ayush Ranjan May 03 '20 at 18:42
  • If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only). So I think that `sleep_a_little` should be getting called first before `ls`, no? – Matt May 03 '20 at 19:08
  • Yes, it will be called before ls. But it is called after fork. So the child process calls it. Why does the parent process (the original process which called `subprocess.Popen()`) hang on the child process while it executes `sleep_a_little`? – Ayush Ranjan May 03 '20 at 19:30

1 Answers1

0

I am having a similar issue, though it appears what is happening is the preexec_fn function is just being run by the parent.

My preexec_fn uses os.setuid and os.setgid to start a user process from a privileged parent.

Calling the whoami utility before spawning a thread then again after shows my parent impersonating the user account and not just the child it has created.

fernandospr
  • 2,976
  • 2
  • 22
  • 43