2

In Cygwin, calling Python3 os.execlp() creates a new process to run external python codes, child's pid is different from that returned by previous os.fork().

I do not know why Cygwin have this weird result.


Running Environment :

  • Cygwin under win10
  • Python 3.6.4

Code :

parent.py

pid = os.fork()
if pid == 0:
     os.execlp('python', 'python', 'child.py')
else:
     print('child is , ', pid)

child.py

print(os.getpid())

When running parent code in Cygwin, the pid numbers returned by two print function are different.

# running result $python fork-exec.py
Child is  6104
Hello from child,  9428

This program runs perfectly under Linux platform.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Rain Win
  • 47
  • 7

2 Answers2

1

First, let's start by stating that being a native Unix/Linux system primitive, fork hasn't any equivalent in Windows, and os.fork doesn't exist in Windows native python for that very reason.

But, Python built for Cygwin is able to make it available because Cygwin emulates fork (how to run python script with os.fork on windows?)

Now, the actual reason why PIDs are different is that os.execlp doesn't behave the same on Windows or on Linux. On windows, execlp is also an emulation and does NOT replace the current process. It just spawns a new process using CreateProcess underneath. Cygwin is able to emulate fork properly, but not exec.

So fork+exec is replaced by CreateProcess on Windows (os.exec on Windows), and os.exec does create a new process, hence the different PIDs.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

the PID is diffrent because cygwin hosts one of them, which is already a process. and windows handles PID's diffrently than most linux distro's.

Timo Herngreen
  • 112
  • 1
  • 9