gpt4 book ai didi

locking - 多个进程之间共享套接字的accept()(基于Apache preforking)

转载 作者:行者123 更新时间:2023-12-02 11:41:44 29 4
gpt4 key购买 nike

我正在编写一些在 Apache 的 MPM prefork 服务器上建模的 Python 代码。我更像是一名应用程序程序员而不是网络程序员,自从我阅读 Stevens 以来已经有 10 年了,所以我正在努力加快理解代码的速度。

我找到了 how Apache's prefork code works, by Sander Temme 的简短描述.

The parent process, which typically runs as root, binds to a socket (usually port 80 or 443). It spawns children, which inherit the open file descriptor for the socket, and change uid and gid to the unprivileged user and group. The children construct a pollset of the listener file descriptors (if there is more than one listener) and watch for activity on it/them. If activity is found, the child calls accept() on the active socket and handles the connection. When it is done with that, it returns to watching the pollset (or listener file descriptor).

Since multiple children are active and they all inherited the same socket file descriptor(s), they will be watching the same pollset. An accept mutex allows only a single child to actually watch the pollset, and once that has found an active socket it will unlock the mutex so the next child can start watching the pollset. If there is only a single listener, that accept mutex is not used and all children will hang in accept().

这几乎就是我正在查看的代码的工作方式,但我不明白一些事情。

1) “ child ”和“听众”有什么区别?我认为每个 child 都是一个监听器,这对于我正在查看的代码来说是正确的,但在 Temme 的描述中可以有“单个监听器”和“ child ”。 child 什么时候会有多个听众?

2) (与 1 相关)这是每进程互斥体还是系统互斥体?就此而言,为什么要有互斥体? Accept(2) 不会在所有监听器之间执行自己的互斥吗?我的研究表明我确实需要一个互斥体,并且互斥体必须遍及整个系统。 (群体、信号量等)

Temme 继续说道:

Children record in a shared memory area (the scoreboard) when they last served a request. Idle children may be killed by the parent process to satisfy MaxSpareServers. If too few children are idle, the parent will spawn children to satisfy MinSpareServers.

3)这个实现有没有好的引用代码(最好是Python)?我找到了Perl的Net::Server::Prefork ,它使用管道而不是记分板的共享内存。我找到了Randal Schwartz的文章它只进行预 fork ,但不进行记分板。

pre-fork example from the Perl Cookbook没有任何围绕 select 的锁定,并且 Chris Siebenmann's Python example说它基于 Apache,但使用配对套接字作为记分板,而不是共享内存,并使用套接字作为控件,包括对给定子项的控制以“接受”。这与 Apache 的描述完全不符。

最佳答案

就 (1) 而言,监听器只是对接受连接的套接字是否存在的引用。由于Apache可以同时接受多个套接字上的连接,例如80/443,因此有多个监听器套接字。每个子进程在需要时都需要监听所有这些套接字。由于accept()一次只能在一个套接字上执行,因此它之前是poll/select,因此知道应该在哪个监听器套接字上执行accept。

对于(2),它是全局或跨进程互斥体。也就是说,一个进程锁定它会阻止其他试图获取同一锁的进程。尽管accept()在技术上会序列化进程,但多个监听器套接字的存在意味着您不能依赖它,因为您事先不知道要在哪个套接字上执行接受。即使在单个监听器套接字的情况下,使用accept互斥锁的原因是,如果有大量进程处理请求,那么如果操作系统唤醒所有进程以查看哪些进程有accept()返回,那么成本可能会相当高。由于处于 prefork 模式的 Apache 可能有 100 多个进程,这可能会导致问题。

因此,如果您只有一个监听器套接字,并且知道只有几个进程想要执行accept() 调用,那么您可以取消跨进程accept 互斥体。

关于locking - 多个进程之间共享套接字的accept()(基于Apache preforking),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1293652/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com