父进程和子进程都可以访问记录器吗? [英] Is a logger accessible to both parent and child processes?

查看:107
本文介绍了父进程和子进程都可以访问记录器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,如果在父进程中配置了记录器,那么子进程也将获得该记录器吗?更清楚地说,在我的应用程序中,我通过执行logger = logging.getlogger()并向其添加处理程序来为父进程配置根记录器.现在,当一个子进程被分叉并且完成了

In python if a logger is configured in the parent process, then will the child process also get that logger? To be more clear, in my application I configure root logger for parent process by doing logger = logging.getlogger() and adding handlers to it. Now when a child process is forked and it does

logger = logging.getlogger()
logger.info("dfsdf")

然后根据父级的根记录器处理所有日志.我没有为孩子配置根记录器.这怎么可能?他们是两个不同的过程,那么他们怎么拥有相同的记录器?

then all the logs are processed according to the parent's root logger. I didn't configure the root logger for the child. How is it possible? They are two different processes then how can they have same logger?

推荐答案

在派生一个进程时,它会继承"父进程的内存,包括记录器配置.

When you fork a process, it 'inherits' the parent process memory, including the logger configuration.

叉子Wikipedia页面中:

fork操作为子代创建一个单独的地址空间.子进程具有父进程所有内存段的精确副本,尽管如果实现了写时复制语义,则可能不会分配实际的物理内存(即,两个进程可能在一段时间内共享相同的物理内存段) .父进程和子进程都具有相同的代码段,但彼此独立执行.

The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process, though if copy-on-write semantics are implemented actual physical memory may not be assigned (i.e., both processes may share the same physical memory segments for a while). Both the parent and child processes possess the same code segments, but execute independently of each other.

这不是Python独有的.对于任何用C,Perl或Python实现的分叉的UNIX进程,都会发生这种情况.

This is not unique to Python; this happens for any UNIX process that is forked, be it implemented in C, Perl or Python.

multiprocessing模块使用此功能(在支持该功能的平台上)快速启动新流程.

The multiprocessing module uses this (on platforms that support it) to spin up new processes quickly.

请注意,继承记录器可能会导致比赛条件; logging模块只知道线程安全性;它使用线程锁来序列化对处理程序的访问,但是该锁不会在进程之间共享(子进程中的所有内容都是副本,并且不是同一对象).

Note that inheriting a logger may lead to race conditions; the logging module only knows about thread-safety; it uses a thread lock to serialize access to handlers, but that lock is not shared across processes (everything in the child process is a copy, and not the same object).

这意味着当您同时记录父级和子级的消息时,随着操作系统在将两个日志条目写入文件时在两个进程之间切换,这些日志条目最终可能混合在一起.

This means that when you log messages from both the parent and child at the same time, the log entries can end up mixed together as the OS switches between the two processes while writing the log entries to the file.

这篇关于父进程和子进程都可以访问记录器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆