Python 分叉一次并获得不同的pid值
在此代码中,输出为:Python 分叉一次并获得不同的pid值,python,python-3.x,Python,Python 3.x,在此代码中,输出为: 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
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")
在从[5063]=>0开始的输出的第二部分中,为什么进程id不同?对于一个子进程,进程id不应该是相同的吗?我希望输出更像:
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
为什么不是这样?对于任何单个进程,进程ID都是相同的,只是因为这些进程同时运行,所以输出混淆了
如果您计算每个进程/序列对的数量,就会看到这一点。您会发现有五个不同的进程ID,每个进程ID都有五个序列标识符,0..4
或者,不要同时运行它们,在打印父信息的行后面插入time.sleep(7)
。然后,您将看到每个线程将在下一个线程开始之前完成,并且输出将反映:
[5060] => 0
[5060] => 1
[5060] => 2
[5060] => 3
[5060] => 4
.
.
.
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