📜 ⬆️ ⬇️

Fork in applications using event loop

There are different ways to implement simultaneous data processing: forks, threads, event loop ... and, as I understand it, they get along pretty lousy.

Let's take the event loop and the fork. Does it make sense to use them in one application? At first glance - of course, there is! The event loop will work normally only if the event handlers execute quickly enough. And as soon as some handler starts to demand a lot of time to work, the first thing that comes to mind is to push it into a separate process (in principle, there are also threads, but in perl it’s hard, so this option is not even considered).

But it is at first glance. And if you dig deeper ...

For example, an application based on the event loop may have a bunch of preset timers that will work after a while and cause certain events. And then fork is made ... and that the spawned process should inherit all these timers and events? Or is it not? Or should inherit them partially, selectively? Rave…
')
One more thing: usually when fork is called in a normal, linear application, we clearly understand the state of the application when fork is called, and how this state should be changed in the child process immediately after the fork call (close extra FDs, deal with signals, etc.) . In the case of the event loop, being in the handler of a particular event, we imagine the general state of the application very roughly, to put it mildly!

In general, in a normal application based on the event loop, all the code is in the event handler functions. Those. when fork is called, we are by definition in such a function. And where will we get out of it, in the spawned process? And where will we get thrown by exception (die)?

More vital example. The application uses epoll to multiplex multiple open sockets. And here, the handler of some event makes a fork. First, the child process will inherit the FD of the epoll itself. Secondly, it will inherit a bunch of sockets (FD) open in the parent. As a result, the parent begins to receive the most unexpected and strange events from the epoll, for various reasons.

Actually, this question is rather abstract, and is not specifically related to Perl or Linux / epoll.

I have tested the Event and Event :: Lib CPAN modules - both do not contain any special fork handling, and do not even mention all these fork-related issues in the documentation.

Perl6 will support the event loop right in the kernel ... and I still don’t see how it can get around these problems.

In general, or I lose sight of something important at the level of concepts, or here a concrete, explosive rake is still there. I will be glad to any explanations on this issue.

Source: https://habr.com/ru/post/17000/


All Articles