Python 中的分叉子进程中的文件描述符关闭

File Descriptors closing in forked subprocesses in Python

在 Python 3.8 应用程序中,父进程负责创建子进程(工作者)并通过 IPC(任务)向它们转发消息。

父进程有自己的记录器,使用 FileHandler 写入文件 main.log 但它也会为每个子进程打开一个记录器,每个子进程都有一个唯一的文件来记录 IPC activity 和错误。

子进程是通过系统调用fork创建的。 IPC 通过 OS 队列完成。见下图说明情况。

问题:虽然在父进程端记录 IPC activity 并将其保存在专用文件中是有益的,但这会打开很多文件描述符 (FD),这些文件描述符 (FD) 都是由每个进程继承的,并且每个后续子进程。

问:如何管理这些FD?在 运行() 上的每个子进程中手动查找并关闭它们?有没有更好的方法?

为那些您不想转移到子进程的文件描述符设置 close-on-exec 标志。通过在打开时设置 O_CLOEXEC 标志,或者稍后使用 fcntl 设置 FD_CLOEXEC.

在你提问之前,O_CLOEXEC != FD_CLOEXEC

您可以将 close_fds=True 传递给您用于启动子进程的任何函数(例如 run):

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in Inheritance of File Descriptors.

来源:https://docs.python.org/3/library/subprocess.html#subprocess.Popen