Reputation:
It seems like subprocess.Popen() and os.fork() both are able to create a child process. I would however like to know what the difference is between both. When would you use which one? I tried looking at their source code but I couldn't find fork()'s source code on my machine and it wasn't totally clear how Popen works on Unix machines.
Could someobody please elaborate?
Thanks
Upvotes: 17
Views: 17316
Reputation: 85757
So I read the documentation for you. Results:
os.fork
only exists on Unix. It creates a child process (by cloning the existing process), but that's all it does. When it returns, you have two (mostly) identical processes, both running the same code, both returning from os.fork
(but the new process gets 0
from os.fork
while the parent process gets the PID of the child process).
subprocess.Popen
is more portable (in particular, it works on Windows). It creates a child process, but you must specify another program that the child process should execute. On Unix, it is implemented by calling os.fork
(to clone the parent process), then os.execvp
(to load the program into the new child process). Because Popen
is all about executing a program, it lets you customize the initial environment of the program. You can redirect its standard handles, specify command line arguments, override environment variables, set its working directory, etc. None of this applies to os.fork
.
In general, subprocess.Popen
is more convenient to use. If you use os.fork
, there's a lot you need to handle manually, and it'll only work on Unix systems. On the other hand, if you actually want to clone a process and not execute a new program, os.fork
is the way to go.
Upvotes: 11
Reputation: 9
Subprocess.popen() spawns a new OS level process.
os.fork() creates another process which will resume at exactly the same place as this one. So within the first loop run, you get a fork after which you have two processes, the "original one" (which gets a pid value of the PID of the child process) and the forked one (which gets a pid value of 0).
Upvotes: 0
Reputation: 81594
subprocess.Popen
let's you execute an arbitrary program/command/executable/whatever in its own process.
os.fork
only allows you to create a child process that will execute the same script from the exact line in which you called it. As its name suggests, it "simply" forks the current process into 2.
os.fork
is only available on Unix, and subprocess.Popen
is cross-platfrom.
Upvotes: 16