Reputation: 319
import os, time
def counting(count):
for i in range(count):
time.sleep(1)
print("[{}] => {}".format(os.getpid(), i))
for i in range(5):
pid = os.fork()
if pid != 0:
print("Process {} parent".format(pid))
else:
counting(5)
os._exit(0)
print("exiting")
In this code, the output is:
Process 5060 parent
Process 5061 parent
Process 5062 parent
Process 5063 parent
Process 5064 parent
>>> [5063]=>0
[5061]=>0
[5062]=>0
[5060]=>0
[5064]=>0
[5063]=>1
[5061]=>1
[5062]=>1
[5060]=>1
[5064]=>1
[5063]=>2
[5061]=>2
[5062]=>2
[5060]=>2
[5064]=>2
[5063]=>3
[5061]=>3
[5062]=>3
[5060]=>3
[5064]=>3
[5061]=>4
[5063]=>4
[5062]=>4
[5060]=>4
[5064]=>4
In the second part of the output beginning from [5063]=>0
, why is the process id different? Isn't the process id supposed to be the same for one child process? I'd expect the output to be more like:
[5060] => 0
[5060] => 1
[5060] => 2
[5060] => 3
[5060] => 4
.
.
.
Why is this not the case?
Upvotes: 1
Views: 57
Reputation: 882596
The process ID is the same for any individual process, it's just that your output is mixed up because those processes are running concurrently.
You'll see this if you count the number of each process/sequence pair. You'll find there are five distinct process IDs and that each of them has all five sequencing identifiers, 0..4
.
Or, don't run them concurrently, by inserting time.sleep(7)
immediately following the line that prints out the parent information. You'll then see that each thread will finish before the next one starts and the output will reflect that:
Process 14303 parent
[14303] => 0
[14303] => 1
[14303] => 2
[14303] => 3
[14303] => 4
Process 14304 parent
[14304] => 0
[14304] => 1
[14304] => 2
[14304] => 3
[14304] => 4
Process 14305 parent
[14305] => 0
[14305] => 1
[14305] => 2
[14305] => 3
[14305] => 4
Process 14306 parent
[14306] => 0
[14306] => 1
[14306] => 2
[14306] => 3
[14306] => 4
Process 14307 parent
[14307] => 0
[14307] => 1
[14307] => 2
[14307] => 3
[14307] => 4
exiting
Upvotes: 2