Fork watcher will not be called if fork() is invoked in prepare watcher callback.

Denis Bilenko denis.bilenko at
Sat May 3 12:49:23 CEST 2014

On Sat, May 3, 2014 at 11:48 AM, Marc Lehmann <schmorp at> wrote:
> On Sat, May 03, 2014 at 10:43:26AM +0800, 李晓岚 <LeeXiaolan+libev at> wrote:
>> > If you have a convincing use case that couldn't be served by starting an
>> > ev_idle watcher and forking from there, we'd be interested in hearing
>> > about it :)
>> Maybe you know gevent. Gevent use libev as its event loop. When new
>> greenlet is spawned, its first run is scheduled in prepare watcher. It
>> is make no sense to forbid invocations of fork in new greenlet's first
>> run, and ev_idle is also not the right choice.
> It makes a lot of sense to forbid invocations of fork in prepare watchers -
> basically, something has to give in: prepare watchers are meant to integrate
> new event sources, and therefore need to be the last thing before blocking,
> so the amount of things that can be done in them is, by necessity, limited.
> For example, there cannot be any watcher invocations anymore, which is the
> problem here.
> You didn't state any reasons on why greenlets have to run inside prepare
> watchers, why they would need to fork the event loop, and why idle
> watchers wouldn't work for them, so at the moment, everything is in favour
> of forbidding event loop forking inside prepare watchers.

To clarify, it works like this:

when someone runs gevent.spawn(args) a new greenlet is created (a
user-level thread). Then there is a per-loop list of all greenlets
that are created and ready to run. The prepare watcher simply goes
over the list and switches into each of those new greenlets, which
then continues until they do something and switch back. What they can
do depend on user code, this might IO (in that case they will set up
IO watcher) or anything else, resulting in greenlet finishing without
a single switch or setting up a watcher and switching back.

It seemed to make sense to do it prepare watcher. Are you saying that
doing this in idle watcher (with highest priority) would be more

More information about the libev mailing list