CSJ
CSJ

Reputation: 2957

python os.fork child process ID is not continuous

I am trying on os.fork function using CPython 3.7.2 Here is the example

def main():
    data = 222

    childPid = os.fork()
    if childPid == -1:
        print('error on fork child')
    elif childPid == 0:
        data *= 3
    else:
        time.sleep(3)

    print("PID=%d data=%d" % (os.getpid(), data))

When I use C language, I always get 2 continuous PID for parent and child. However in python, I always get PID which are not continuous( for example here I got 21475 and 21442).

PID=21475 data=666
PID=21442 data=222

Don't understand how it behave not same.

Upvotes: 3

Views: 510

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

PIDs are not guaranteed to be consecutive, although they typically are (on Linux). If a PID is already in use, it will be skipped.

If you saw consecutive PIDs when testing C code, it's because you happened to not come across an in-use PID. There should be no difference in behavior between fork() in C and os.fork() in Python.

Upvotes: 5

Related Questions