在分配流程时,请考虑以下情形:
1)我们为IPC双向通信打开两个管道 2)假设它们具有(3,4)和(5,6)作为文件描述符 3)我们把过程分到中间的某个地方 4)我们执行子进程
现在,发生的事情是这两个进程完全相互独立,然后子进程现在拥有自己的地址空间,并且是一个全新的进程。
现在,我的问题是,管道(/文件描述符)如何存在于 Exec ed进程中?因为,像这样打开的管道用于 exec ed和父进程进行通信。
我看到这种情况的唯一方法就是当文件描述符对机器是全局的时候,我认为是不可能发生的,因为这会产生冲突。
在此代码的IDE中:
import os
from multiprocessing import Process, Pipe
def sender(pipe):
"""
send object to parent on anonymous pipe
"""
pipe.send(['spam']+[42, 'eggs'])
pipe.close()
def talker(pipe):
"""
send and receive objects on a pipe
"""
pipe.send(dict(name = 'Bob', spam = 42))
reply = pipe.recv()
print('talker got: ', reply)
if __name__ == '__main__':
(parentEnd, childEnd) = Pipe()
Process(target = sender, args = (childEnd,)).start()
print("parent got: ", parentEnd.recv())
parentEnd.close()
(parentEnd, childEnd) = Pipe()
child = Process(target = talker, args = (childEnd,))
##############################from here
child.start()
print('From talker Parent got:', parentEnd.recv())
parentEnd.send({x * 2 for x in 'spam'})
child.join()
############################## to here
print('parent exit')
有两个进程在运行,但只有一个进程的输出可以在空闲中看到,而不是两个进程。但是,在终端中,它就像stdout一样也是共享的。
答案 0 :(得分:1)
复制进程文件描述符表的实际工作由更通用的clone()
系统调用标志CLONE_FILES
(实际上不是由{{1}设置)调节}):
fork()
除非文件被打开或标有CLONE_FILES (since Linux 2.0)
...
If CLONE_FILES is not set, the child process inherits a copy of all file
descriptors opened in the calling process at the time of clone(). (The dupli-
cated file descriptors in the child refer to the same open file descriptions
(see open(2)) as the corresponding file descriptors in the calling process.)
Subsequent operations that open or close file descriptors, or change file
descriptor flags, performed by either the calling process or the child process
do not affect the other process.
或O_CLOEXEC
标志,否则 execve()
不会触及文件描述符,在这种情况下,这些描述符将被关闭:
FD_CLOEXEC