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")
在此代码中,输出为:
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
在从[5063]=>0
开始的输出的第二部分中,为什么进程ID不同?一个子进程的进程 ID 不应该是相同的吗?我希望输出更像是:
[5060] => 0
[5060] => 1
[5060] => 2
[5060] => 3
[5060] => 4
.
.
.
为什么情况并非如此?
最佳答案
任何单独进程的进程 ID 都是相同的,只是您的输出会混合在一起,因为这些进程是同时运行的。
如果您计算每个进程/序列对的数量,您就会看到这一点。您会发现有五个不同的进程 ID,并且每个都有所有五个排序标识符,0..4
。
或者,不要同时运行它们,方法是在打印出父信息的行之后立即插入 time.sleep(7)
。然后,您将看到每个线程将在下一个线程开始之前完成,并且输出将反射(reflect)这一点:
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
关于python - fork一次并获得不同的pid值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46029657/