|
|
1 | NAME |
|
|
2 | AnyEvent::Fork - everything you wanted to use fork() for, but couldn't |
|
|
3 | |
|
|
4 | SYNOPSIS |
|
|
5 | use AnyEvent::Fork; |
|
|
6 | |
|
|
7 | AnyEvent::Fork |
|
|
8 | ->new |
|
|
9 | ->require ("MyModule") |
|
|
10 | ->run ("MyModule::server", my $cv = AE::cv); |
|
|
11 | |
|
|
12 | my $fh = $cv->recv; |
|
|
13 | |
|
|
14 | DESCRIPTION |
|
|
15 | This module allows you to create new processes, without actually forking |
|
|
16 | them from your current process (avoiding the problems of forking), but |
|
|
17 | preserving most of the advantages of fork. |
|
|
18 | |
|
|
19 | It can be used to create new worker processes or new independent |
|
|
20 | subprocesses for short- and long-running jobs, process pools (e.g. for |
|
|
21 | use in pre-forked servers) but also to spawn new external processes |
|
|
22 | (such as CGI scripts from a web server), which can be faster (and more |
|
|
23 | well behaved) than using fork+exec in big processes. |
|
|
24 | |
|
|
25 | Special care has been taken to make this module useful from other |
|
|
26 | modules, while still supporting specialised environments such as |
|
|
27 | App::Staticperl or PAR::Packer. |
|
|
28 | |
|
|
29 | WHAT THIS MODULE IS NOT |
|
|
30 | This module only creates processes and lets you pass file handles and |
|
|
31 | strings to it, and run perl code. It does not implement any kind of RPC |
|
|
32 | - there is no back channel from the process back to you, and there is no |
|
|
33 | RPC or message passing going on. |
|
|
34 | |
|
|
35 | If you need some form of RPC, you can either implement it yourself in |
|
|
36 | whatever way you like, use some message-passing module such as |
|
|
37 | AnyEvent::MP, some pipe such as AnyEvent::ZeroMQ, use AnyEvent::Handle |
|
|
38 | on both sides to send e.g. JSON or Storable messages, and so on. |
|
|
39 | |
|
|
40 | COMPARISON TO OTHER MODULES |
|
|
41 | There is an abundance of modules on CPAN that do "something fork", such |
|
|
42 | as Parallel::ForkManager, AnyEvent::ForkManager, AnyEvent::Worker or |
|
|
43 | AnyEvent::Subprocess. There are modules that implement their own process |
|
|
44 | management, such as AnyEvent::DBI. |
|
|
45 | |
|
|
46 | The problems that all these modules try to solve are real, however, none |
|
|
47 | of them (from what I have seen) tackle the very real problems of |
|
|
48 | unwanted memory sharing, efficiency, not being able to use event |
|
|
49 | processing or similar modules in the processes they create. |
|
|
50 | |
|
|
51 | This module doesn't try to replace any of them - instead it tries to |
|
|
52 | solve the problem of creating processes with a minimum of fuss and |
|
|
53 | overhead (and also luxury). Ideally, most of these would use |
|
|
54 | AnyEvent::Fork internally, except they were written before AnyEvent:Fork |
|
|
55 | was available, so obviously had to roll their own. |
|
|
56 | |
|
|
57 | PROBLEM STATEMENT |
|
|
58 | There are two traditional ways to implement parallel processing on UNIX |
|
|
59 | like operating systems - fork and process, and fork+exec and process. |
|
|
60 | They have different advantages and disadvantages that I describe below, |
|
|
61 | together with how this module tries to mitigate the disadvantages. |
|
|
62 | |
|
|
63 | Forking from a big process can be very slow. |
|
|
64 | A 5GB process needs 0.05s to fork on my 3.6GHz amd64 GNU/Linux box. |
|
|
65 | This overhead is often shared with exec (because you have to fork |
|
|
66 | first), but in some circumstances (e.g. when vfork is used), |
|
|
67 | fork+exec can be much faster. |
|
|
68 | |
|
|
69 | This module can help here by telling a small(er) helper process to |
|
|
70 | fork, which is faster then forking the main process, and also uses |
|
|
71 | vfork where possible. This gives the speed of vfork, with the |
|
|
72 | flexibility of fork. |
|
|
73 | |
|
|
74 | Forking usually creates a copy-on-write copy of the parent process. |
|
|
75 | For example, modules or data files that are loaded will not use |
|
|
76 | additional memory after a fork. When exec'ing a new process, modules |
|
|
77 | and data files might need to be loaded again, at extra CPU and |
|
|
78 | memory cost. But when forking, literally all data structures are |
|
|
79 | copied - if the program frees them and replaces them by new data, |
|
|
80 | the child processes will retain the old version even if it isn't |
|
|
81 | used, which can suddenly and unexpectedly increase memory usage when |
|
|
82 | freeing memory. |
|
|
83 | |
|
|
84 | The trade-off is between more sharing with fork (which can be good |
|
|
85 | or bad), and no sharing with exec. |
|
|
86 | |
|
|
87 | This module allows the main program to do a controlled fork, and |
|
|
88 | allows modules to exec processes safely at any time. When creating a |
|
|
89 | custom process pool you can take advantage of data sharing via fork |
|
|
90 | without risking to share large dynamic data structures that will |
|
|
91 | blow up child memory usage. |
|
|
92 | |
|
|
93 | In other words, this module puts you into control over what is being |
|
|
94 | shared and what isn't, at all times. |
|
|
95 | |
|
|
96 | Exec'ing a new perl process might be difficult. |
|
|
97 | For example, it is not easy to find the correct path to the perl |
|
|
98 | interpreter - $^X might not be a perl interpreter at all. |
|
|
99 | |
|
|
100 | This module tries hard to identify the correct path to the perl |
|
|
101 | interpreter. With a cooperative main program, exec'ing the |
|
|
102 | interpreter might not even be necessary, but even without help from |
|
|
103 | the main program, it will still work when used from a module. |
|
|
104 | |
|
|
105 | Exec'ing a new perl process might be slow, as all necessary modules have |
|
|
106 | to be loaded from disk again, with no guarantees of success. |
|
|
107 | Long running processes might run into problems when perl is upgraded |
|
|
108 | and modules are no longer loadable because they refer to a different |
|
|
109 | perl version, or parts of a distribution are newer than the ones |
|
|
110 | already loaded. |
|
|
111 | |
|
|
112 | This module supports creating pre-initialised perl processes to be |
|
|
113 | used as a template for new processes. |
|
|
114 | |
|
|
115 | Forking might be impossible when a program is running. |
|
|
116 | For example, POSIX makes it almost impossible to fork from a |
|
|
117 | multi-threaded program while doing anything useful in the child - in |
|
|
118 | fact, if your perl program uses POSIX threads (even indirectly via |
|
|
119 | e.g. IO::AIO or threads), you cannot call fork on the perl level |
|
|
120 | anymore without risking corruption issues on a number of operating |
|
|
121 | systems. |
|
|
122 | |
|
|
123 | This module can safely fork helper processes at any time, by calling |
|
|
124 | fork+exec in C, in a POSIX-compatible way (via Proc::FastSpawn). |
|
|
125 | |
|
|
126 | Parallel processing with fork might be inconvenient or difficult to |
|
|
127 | implement. Modules might not work in both parent and child. |
|
|
128 | For example, when a program uses an event loop and creates watchers |
|
|
129 | it becomes very hard to use the event loop from a child program, as |
|
|
130 | the watchers already exist but are only meaningful in the parent. |
|
|
131 | Worse, a module might want to use such a module, not knowing whether |
|
|
132 | another module or the main program also does, leading to problems. |
|
|
133 | |
|
|
134 | Apart from event loops, graphical toolkits also commonly fall into |
|
|
135 | the "unsafe module" category, or just about anything that |
|
|
136 | communicates with the external world, such as network libraries and |
|
|
137 | file I/O modules, which usually don't like being copied and then |
|
|
138 | allowed to continue in two processes. |
|
|
139 | |
|
|
140 | With this module only the main program is allowed to create new |
|
|
141 | processes by forking (because only the main program can know when it |
|
|
142 | is still safe to do so) - all other processes are created via |
|
|
143 | fork+exec, which makes it possible to use modules such as event |
|
|
144 | loops or window interfaces safely. |
|
|
145 | |
|
|
146 | EXAMPLES |
|
|
147 | Create a single new process, tell it to run your worker function. |
|
|
148 | AnyEvent::Fork |
|
|
149 | ->new |
|
|
150 | ->require ("MyModule") |
|
|
151 | ->run ("MyModule::worker, sub { |
|
|
152 | my ($master_filehandle) = @_; |
|
|
153 | |
|
|
154 | # now $master_filehandle is connected to the |
|
|
155 | # $slave_filehandle in the new process. |
|
|
156 | }); |
|
|
157 | |
|
|
158 | "MyModule" might look like this: |
|
|
159 | |
|
|
160 | package MyModule; |
|
|
161 | |
|
|
162 | sub worker { |
|
|
163 | my ($slave_filehandle) = @_; |
|
|
164 | |
|
|
165 | # now $slave_filehandle is connected to the $master_filehandle |
|
|
166 | # in the original prorcess. have fun! |
|
|
167 | } |
|
|
168 | |
|
|
169 | Create a pool of server processes all accepting on the same socket. |
|
|
170 | # create listener socket |
|
|
171 | my $listener = ...; |
|
|
172 | |
|
|
173 | # create a pool template, initialise it and give it the socket |
|
|
174 | my $pool = AnyEvent::Fork |
|
|
175 | ->new |
|
|
176 | ->require ("Some::Stuff", "My::Server") |
|
|
177 | ->send_fh ($listener); |
|
|
178 | |
|
|
179 | # now create 10 identical workers |
|
|
180 | for my $id (1..10) { |
|
|
181 | $pool |
|
|
182 | ->fork |
|
|
183 | ->send_arg ($id) |
|
|
184 | ->run ("My::Server::run"); |
|
|
185 | } |
|
|
186 | |
|
|
187 | # now do other things - maybe use the filehandle provided by run |
|
|
188 | # to wait for the processes to die. or whatever. |
|
|
189 | |
|
|
190 | "My::Server" might look like this: |
|
|
191 | |
|
|
192 | package My::Server; |
|
|
193 | |
|
|
194 | sub run { |
|
|
195 | my ($slave, $listener, $id) = @_; |
|
|
196 | |
|
|
197 | close $slave; # we do not use the socket, so close it to save resources |
|
|
198 | |
|
|
199 | # we could go ballistic and use e.g. AnyEvent here, or IO::AIO, |
|
|
200 | # or anything we usually couldn't do in a process forked normally. |
|
|
201 | while (my $socket = $listener->accept) { |
|
|
202 | # do sth. with new socket |
|
|
203 | } |
|
|
204 | } |
|
|
205 | |
|
|
206 | use AnyEvent::Fork as a faster fork+exec |
|
|
207 | This runs "/bin/echo hi", with stdandard output redirected to /tmp/log |
|
|
208 | and standard error redirected to the communications socket. It is |
|
|
209 | usually faster than fork+exec, but still lets you prepare the |
|
|
210 | environment. |
|
|
211 | |
|
|
212 | open my $output, ">/tmp/log" or die "$!"; |
|
|
213 | |
|
|
214 | AnyEvent::Fork |
|
|
215 | ->new |
|
|
216 | ->eval (' |
|
|
217 | # compile a helper function for later use |
|
|
218 | sub run { |
|
|
219 | my ($fh, $output, @cmd) = @_; |
|
|
220 | |
|
|
221 | # perl will clear close-on-exec on STDOUT/STDERR |
|
|
222 | open STDOUT, ">&", $output or die; |
|
|
223 | open STDERR, ">&", $fh or die; |
|
|
224 | |
|
|
225 | exec @cmd; |
|
|
226 | } |
|
|
227 | ') |
|
|
228 | ->send_fh ($output) |
|
|
229 | ->send_arg ("/bin/echo", "hi") |
|
|
230 | ->run ("run", my $cv = AE::cv); |
|
|
231 | |
|
|
232 | my $stderr = $cv->recv; |
|
|
233 | |
|
|
234 | CONCEPTS |
|
|
235 | This module can create new processes either by executing a new perl |
|
|
236 | process, or by forking from an existing "template" process. |
|
|
237 | |
|
|
238 | Each such process comes with its own file handle that can be used to |
|
|
239 | communicate with it (it's actually a socket - one end in the new |
|
|
240 | process, one end in the main process), and among the things you can do |
|
|
241 | in it are load modules, fork new processes, send file handles to it, and |
|
|
242 | execute functions. |
|
|
243 | |
|
|
244 | There are multiple ways to create additional processes to execute some |
|
|
245 | jobs: |
|
|
246 | |
|
|
247 | fork a new process from the "default" template process, load code, run |
|
|
248 | it |
|
|
249 | This module has a "default" template process which it executes when |
|
|
250 | it is needed the first time. Forking from this process shares the |
|
|
251 | memory used for the perl interpreter with the new process, but |
|
|
252 | loading modules takes time, and the memory is not shared with |
|
|
253 | anything else. |
|
|
254 | |
|
|
255 | This is ideal for when you only need one extra process of a kind, |
|
|
256 | with the option of starting and stopping it on demand. |
|
|
257 | |
|
|
258 | Example: |
|
|
259 | |
|
|
260 | AnyEvent::Fork |
|
|
261 | ->new |
|
|
262 | ->require ("Some::Module") |
|
|
263 | ->run ("Some::Module::run", sub { |
|
|
264 | my ($fork_fh) = @_; |
|
|
265 | }); |
|
|
266 | |
|
|
267 | fork a new template process, load code, then fork processes off of it |
|
|
268 | and run the code |
|
|
269 | When you need to have a bunch of processes that all execute the same |
|
|
270 | (or very similar) tasks, then a good way is to create a new template |
|
|
271 | process for them, loading all the modules you need, and then create |
|
|
272 | your worker processes from this new template process. |
|
|
273 | |
|
|
274 | This way, all code (and data structures) that can be shared (e.g. |
|
|
275 | the modules you loaded) is shared between the processes, and each |
|
|
276 | new process consumes relatively little memory of its own. |
|
|
277 | |
|
|
278 | The disadvantage of this approach is that you need to create a |
|
|
279 | template process for the sole purpose of forking new processes from |
|
|
280 | it, but if you only need a fixed number of processes you can create |
|
|
281 | them, and then destroy the template process. |
|
|
282 | |
|
|
283 | Example: |
|
|
284 | |
|
|
285 | my $template = AnyEvent::Fork->new->require ("Some::Module"); |
|
|
286 | |
|
|
287 | for (1..10) { |
|
|
288 | $template->fork->run ("Some::Module::run", sub { |
|
|
289 | my ($fork_fh) = @_; |
|
|
290 | }); |
|
|
291 | } |
|
|
292 | |
|
|
293 | # at this point, you can keep $template around to fork new processes |
|
|
294 | # later, or you can destroy it, which causes it to vanish. |
|
|
295 | |
|
|
296 | execute a new perl interpreter, load some code, run it |
|
|
297 | This is relatively slow, and doesn't allow you to share memory |
|
|
298 | between multiple processes. |
|
|
299 | |
|
|
300 | The only advantage is that you don't have to have a template process |
|
|
301 | hanging around all the time to fork off some new processes, which |
|
|
302 | might be an advantage when there are long time spans where no extra |
|
|
303 | processes are needed. |
|
|
304 | |
|
|
305 | Example: |
|
|
306 | |
|
|
307 | AnyEvent::Fork |
|
|
308 | ->new_exec |
|
|
309 | ->require ("Some::Module") |
|
|
310 | ->run ("Some::Module::run", sub { |
|
|
311 | my ($fork_fh) = @_; |
|
|
312 | }); |
|
|
313 | |
|
|
314 | THE "AnyEvent::Fork" CLASS |
|
|
315 | This module exports nothing, and only implements a single class - |
|
|
316 | "AnyEvent::Fork". |
|
|
317 | |
|
|
318 | There are two class constructors that both create new processes - "new" |
|
|
319 | and "new_exec". The "fork" method creates a new process by forking an |
|
|
320 | existing one and could be considered a third constructor. |
|
|
321 | |
|
|
322 | Most of the remaining methods deal with preparing the new process, by |
|
|
323 | loading code, evaluating code and sending data to the new process. They |
|
|
324 | usually return the process object, so you can chain method calls. |
|
|
325 | |
|
|
326 | If a process object is destroyed before calling its "run" method, then |
|
|
327 | the process simply exits. After "run" is called, all responsibility is |
|
|
328 | passed to the specified function. |
|
|
329 | |
|
|
330 | As long as there is any outstanding work to be done, process objects |
|
|
331 | resist being destroyed, so there is no reason to store them unless you |
|
|
332 | need them later - configure and forget works just fine. |
|
|
333 | |
|
|
334 | my $proc = new AnyEvent::Fork |
|
|
335 | |
|
|
336 | Create a new "empty" perl interpreter process and returns its |
|
|
337 | process object for further manipulation. |
|
|
338 | |
|
|
339 | The new process is forked from a template process that is kept |
|
|
340 | around for this purpose. When it doesn't exist yet, it is created by |
|
|
341 | a call to "new_exec" first and then stays around for future calls. |
|
|
342 | |
|
|
343 | $new_proc = $proc->fork |
|
|
344 | |
|
|
345 | Forks $proc, creating a new process, and returns the process object |
|
|
346 | of the new process. |
|
|
347 | |
|
|
348 | If any of the "send_" functions have been called before fork, then |
|
|
349 | they will be cloned in the child. For example, in a pre-forked |
|
|
350 | server, you might "send_fh" the listening socket into the template |
|
|
351 | process, and then keep calling "fork" and "run". |
|
|
352 | |
|
|
353 | my $proc = new_exec AnyEvent::Fork |
|
|
354 | |
|
|
355 | Create a new "empty" perl interpreter process and returns its |
|
|
356 | process object for further manipulation. |
|
|
357 | |
|
|
358 | Unlike the "new" method, this method *always* spawns a new perl |
|
|
359 | process (except in some cases, see AnyEvent::Fork::Early for |
|
|
360 | details). This reduces the amount of memory sharing that is |
|
|
361 | possible, and is also slower. |
|
|
362 | |
|
|
363 | You should use "new" whenever possible, except when having a |
|
|
364 | template process around is unacceptable. |
|
|
365 | |
|
|
366 | The path to the perl interpreter is divined using various methods - |
|
|
367 | first $^X is investigated to see if the path ends with something |
|
|
368 | that sounds as if it were the perl interpreter. Failing this, the |
|
|
369 | module falls back to using $Config::Config{perlpath}. |
|
|
370 | |
|
|
371 | $pid = $proc->pid |
|
|
372 | |
|
|
373 | Returns the process id of the process *iff it is a direct child of |
|
|
374 | the process running AnyEvent::Fork*, and "undef" otherwise. |
|
|
375 | |
|
|
376 | Normally, only processes created via "AnyEvent::Fork->new_exec" and |
|
|
377 | AnyEvent::Fork::Template are direct children, and you are |
|
|
378 | responsible to clean up their zombies when they die. |
|
|
379 | |
|
|
380 | All other processes are not direct children, and will be cleaned up |
|
|
381 | by AnyEvent::Fork itself. |
|
|
382 | |
|
|
383 | $proc = $proc->eval ($perlcode, @args) |
|
|
384 | |
|
|
385 | Evaluates the given $perlcode as ... perl code, while setting @_ to |
|
|
386 | the strings specified by @args, in the "main" package. |
|
|
387 | |
|
|
388 | This call is meant to do any custom initialisation that might be |
|
|
389 | required (for example, the "require" method uses it). It's not |
|
|
390 | supposed to be used to completely take over the process, use "run" |
|
|
391 | for that. |
|
|
392 | |
|
|
393 | The code will usually be executed after this call returns, and there |
|
|
394 | is no way to pass anything back to the calling process. Any |
|
|
395 | evaluation errors will be reported to stderr and cause the process |
|
|
396 | to exit. |
|
|
397 | |
|
|
398 | If you want to execute some code (that isn't in a module) to take |
|
|
399 | over the process, you should compile a function via "eval" first, |
|
|
400 | and then call it via "run". This also gives you access to any |
|
|
401 | arguments passed via the "send_xxx" methods, such as file handles. |
|
|
402 | See the "use AnyEvent::Fork as a faster fork+exec" example to see it |
|
|
403 | in action. |
|
|
404 | |
|
|
405 | Returns the process object for easy chaining of method calls. |
|
|
406 | |
|
|
407 | $proc = $proc->require ($module, ...) |
|
|
408 | |
|
|
409 | Tries to load the given module(s) into the process |
|
|
410 | |
|
|
411 | Returns the process object for easy chaining of method calls. |
|
|
412 | |
|
|
413 | $proc = $proc->send_fh ($handle, ...) |
|
|
414 | |
|
|
415 | Send one or more file handles (*not* file descriptors) to the |
|
|
416 | process, to prepare a call to "run". |
|
|
417 | |
|
|
418 | The process object keeps a reference to the handles until they have |
|
|
419 | been passed over to the process, so you must not explicitly close |
|
|
420 | the handles. This is most easily accomplished by simply not storing |
|
|
421 | the file handles anywhere after passing them to this method - when |
|
|
422 | AnyEvent::Fork is finished using them, perl will automatically close |
|
|
423 | them. |
|
|
424 | |
|
|
425 | Returns the process object for easy chaining of method calls. |
|
|
426 | |
|
|
427 | Example: pass a file handle to a process, and release it without |
|
|
428 | closing. It will be closed automatically when it is no longer used. |
|
|
429 | |
|
|
430 | $proc->send_fh ($my_fh); |
|
|
431 | undef $my_fh; # free the reference if you want, but DO NOT CLOSE IT |
|
|
432 | |
|
|
433 | $proc = $proc->send_arg ($string, ...) |
|
|
434 | |
|
|
435 | Send one or more argument strings to the process, to prepare a call |
|
|
436 | to "run". The strings can be any octet strings. |
|
|
437 | |
|
|
438 | The protocol is optimised to pass a moderate number of relatively |
|
|
439 | short strings - while you can pass up to 4GB of data in one go, this |
|
|
440 | is more meant to pass some ID information or other startup info, not |
|
|
441 | big chunks of data. |
|
|
442 | |
|
|
443 | Returns the process object for easy chaining of method calls. |
|
|
444 | |
|
|
445 | $proc->run ($func, $cb->($fh)) |
|
|
446 | |
|
|
447 | Enter the function specified by the function name in $func in the |
|
|
448 | process. The function is called with the communication socket as |
|
|
449 | first argument, followed by all file handles and string arguments |
|
|
450 | sent earlier via "send_fh" and "send_arg" methods, in the order they |
|
|
451 | were called. |
|
|
452 | |
|
|
453 | The process object becomes unusable on return from this function - |
|
|
454 | any further method calls result in undefined behaviour. |
|
|
455 | |
|
|
456 | The function name should be fully qualified, but if it isn't, it |
|
|
457 | will be looked up in the "main" package. |
|
|
458 | |
|
|
459 | If the called function returns, doesn't exist, or any error occurs, |
|
|
460 | the process exits. |
|
|
461 | |
|
|
462 | Preparing the process is done in the background - when all commands |
|
|
463 | have been sent, the callback is invoked with the local |
|
|
464 | communications socket as argument. At this point you can start using |
|
|
465 | the socket in any way you like. |
|
|
466 | |
|
|
467 | If the communication socket isn't used, it should be closed on both |
|
|
468 | sides, to save on kernel memory. |
|
|
469 | |
|
|
470 | The socket is non-blocking in the parent, and blocking in the newly |
|
|
471 | created process. The close-on-exec flag is set in both. |
|
|
472 | |
|
|
473 | Even if not used otherwise, the socket can be a good indicator for |
|
|
474 | the existence of the process - if the other process exits, you get a |
|
|
475 | readable event on it, because exiting the process closes the socket |
|
|
476 | (if it didn't create any children using fork). |
|
|
477 | |
|
|
478 | Example: create a template for a process pool, pass a few strings, |
|
|
479 | some file handles, then fork, pass one more string, and run some |
|
|
480 | code. |
|
|
481 | |
|
|
482 | my $pool = AnyEvent::Fork |
|
|
483 | ->new |
|
|
484 | ->send_arg ("str1", "str2") |
|
|
485 | ->send_fh ($fh1, $fh2); |
|
|
486 | |
|
|
487 | for (1..2) { |
|
|
488 | $pool |
|
|
489 | ->fork |
|
|
490 | ->send_arg ("str3") |
|
|
491 | ->run ("Some::function", sub { |
|
|
492 | my ($fh) = @_; |
|
|
493 | |
|
|
494 | # fh is nonblocking, but we trust that the OS can accept these |
|
|
495 | # few octets anyway. |
|
|
496 | syswrite $fh, "hi #$_\n"; |
|
|
497 | |
|
|
498 | # $fh is being closed here, as we don't store it anywhere |
|
|
499 | }); |
|
|
500 | } |
|
|
501 | |
|
|
502 | # Some::function might look like this - all parameters passed before fork |
|
|
503 | # and after will be passed, in order, after the communications socket. |
|
|
504 | sub Some::function { |
|
|
505 | my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_; |
|
|
506 | |
|
|
507 | print scalar <$fh>; # prints "hi #1\n" and "hi #2\n" in any order |
|
|
508 | } |
|
|
509 | |
|
|
510 | PERFORMANCE |
|
|
511 | Now for some unscientific benchmark numbers (all done on an amd64 |
|
|
512 | GNU/Linux box). These are intended to give you an idea of the relative |
|
|
513 | performance you can expect, they are not meant to be absolute |
|
|
514 | performance numbers. |
|
|
515 | |
|
|
516 | OK, so, I ran a simple benchmark that creates a socket pair, forks, |
|
|
517 | calls exit in the child and waits for the socket to close in the parent. |
|
|
518 | I did load AnyEvent, EV and AnyEvent::Fork, for a total process size of |
|
|
519 | 5100kB. |
|
|
520 | |
|
|
521 | 2079 new processes per second, using manual socketpair + fork |
|
|
522 | |
|
|
523 | Then I did the same thing, but instead of calling fork, I called |
|
|
524 | AnyEvent::Fork->new->run ("CORE::exit") and then again waited for the |
|
|
525 | socket form the child to close on exit. This does the same thing as |
|
|
526 | manual socket pair + fork, except that what is forked is the template |
|
|
527 | process (2440kB), and the socket needs to be passed to the server at the |
|
|
528 | other end of the socket first. |
|
|
529 | |
|
|
530 | 2307 new processes per second, using AnyEvent::Fork->new |
|
|
531 | |
|
|
532 | And finally, using "new_exec" instead "new", using vforks+execs to exec |
|
|
533 | a new perl interpreter and compile the small server each time, I get: |
|
|
534 | |
|
|
535 | 479 vfork+execs per second, using AnyEvent::Fork->new_exec |
|
|
536 | |
|
|
537 | So how can "AnyEvent->new" be faster than a standard fork, even though |
|
|
538 | it uses the same operations, but adds a lot of overhead? |
|
|
539 | |
|
|
540 | The difference is simply the process size: forking the 5MB process takes |
|
|
541 | so much longer than forking the 2.5MB template process that the extra |
|
|
542 | overhead introduced is canceled out. |
|
|
543 | |
|
|
544 | If the benchmark process grows, the normal fork becomes even slower: |
|
|
545 | |
|
|
546 | 1340 new processes, manual fork of a 20MB process |
|
|
547 | 731 new processes, manual fork of a 200MB process |
|
|
548 | 235 new processes, manual fork of a 2000MB process |
|
|
549 | |
|
|
550 | What that means (to me) is that I can use this module without having a |
|
|
551 | bad conscience because of the extra overhead required to start new |
|
|
552 | processes. |
|
|
553 | |
|
|
554 | TYPICAL PROBLEMS |
|
|
555 | This section lists typical problems that remain. I hope by recognising |
|
|
556 | them, most can be avoided. |
|
|
557 | |
|
|
558 | leaked file descriptors for exec'ed processes |
|
|
559 | POSIX systems inherit file descriptors by default when exec'ing a |
|
|
560 | new process. While perl itself laudably sets the close-on-exec flags |
|
|
561 | on new file handles, most C libraries don't care, and even if all |
|
|
562 | cared, it's often not possible to set the flag in a race-free |
|
|
563 | manner. |
|
|
564 | |
|
|
565 | That means some file descriptors can leak through. And since it |
|
|
566 | isn't possible to know which file descriptors are "good" and |
|
|
567 | "necessary" (or even to know which file descriptors are open), there |
|
|
568 | is no good way to close the ones that might harm. |
|
|
569 | |
|
|
570 | As an example of what "harm" can be done consider a web server that |
|
|
571 | accepts connections and afterwards some module uses AnyEvent::Fork |
|
|
572 | for the first time, causing it to fork and exec a new process, which |
|
|
573 | might inherit the network socket. When the server closes the socket, |
|
|
574 | it is still open in the child (which doesn't even know that) and the |
|
|
575 | client might conclude that the connection is still fine. |
|
|
576 | |
|
|
577 | For the main program, there are multiple remedies available - |
|
|
578 | AnyEvent::Fork::Early is one, creating a process early and not using |
|
|
579 | "new_exec" is another, as in both cases, the first process can be |
|
|
580 | exec'ed well before many random file descriptors are open. |
|
|
581 | |
|
|
582 | In general, the solution for these kind of problems is to fix the |
|
|
583 | libraries or the code that leaks those file descriptors. |
|
|
584 | |
|
|
585 | Fortunately, most of these leaked descriptors do no harm, other than |
|
|
586 | sitting on some resources. |
|
|
587 | |
|
|
588 | leaked file descriptors for fork'ed processes |
|
|
589 | Normally, AnyEvent::Fork does start new processes by exec'ing them, |
|
|
590 | which closes file descriptors not marked for being inherited. |
|
|
591 | |
|
|
592 | However, AnyEvent::Fork::Early and AnyEvent::Fork::Template offer a |
|
|
593 | way to create these processes by forking, and this leaks more file |
|
|
594 | descriptors than exec'ing them, as there is no way to mark |
|
|
595 | descriptors as "close on fork". |
|
|
596 | |
|
|
597 | An example would be modules like EV, IO::AIO or Gtk2. Both create |
|
|
598 | pipes for internal uses, and Gtk2 might open a connection to the X |
|
|
599 | server. EV and IO::AIO can deal with fork, but Gtk2 might have |
|
|
600 | trouble with a fork. |
|
|
601 | |
|
|
602 | The solution is to either not load these modules before use'ing |
|
|
603 | AnyEvent::Fork::Early or AnyEvent::Fork::Template, or to delay |
|
|
604 | initialising them, for example, by calling "init Gtk2" manually. |
|
|
605 | |
|
|
606 | exiting calls object destructors |
|
|
607 | This only applies to users of AnyEvent::Fork:Early and |
|
|
608 | AnyEvent::Fork::Template, or when initialiasing code creates objects |
|
|
609 | that reference external resources. |
|
|
610 | |
|
|
611 | When a process created by AnyEvent::Fork exits, it might do so by |
|
|
612 | calling exit, or simply letting perl reach the end of the program. |
|
|
613 | At which point Perl runs all destructors. |
|
|
614 | |
|
|
615 | Not all destructors are fork-safe - for example, an object that |
|
|
616 | represents the connection to an X display might tell the X server to |
|
|
617 | free resources, which is inconvenient when the "real" object in the |
|
|
618 | parent still needs to use them. |
|
|
619 | |
|
|
620 | This is obviously not a problem for AnyEvent::Fork::Early, as you |
|
|
621 | used it as the very first thing, right? |
|
|
622 | |
|
|
623 | It is a problem for AnyEvent::Fork::Template though - and the |
|
|
624 | solution is to not create objects with nontrivial destructors that |
|
|
625 | might have an effect outside of Perl. |
|
|
626 | |
|
|
627 | PORTABILITY NOTES |
|
|
628 | Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a |
|
|
629 | nop, and ::Template is not going to work), and it cost a lot of blood |
|
|
630 | and sweat to make it so, mostly due to the bloody broken perl that |
|
|
631 | nobody seems to care about. The fork emulation is a bad joke - I have |
|
|
632 | yet to see something useful that you can do with it without running into |
|
|
633 | memory corruption issues or other braindamage. Hrrrr. |
|
|
634 | |
|
|
635 | Cygwin perl is not supported at the moment due to some hilarious |
|
|
636 | shortcomings of its API - see IO::FDPoll for more details. |
|
|
637 | |
|
|
638 | SEE ALSO |
|
|
639 | AnyEvent::Fork::Early (to avoid executing a perl interpreter), |
|
|
640 | AnyEvent::Fork::Template (to create a process by forking the main |
|
|
641 | program at a convenient time). |
|
|
642 | |
|
|
643 | AUTHOR |
|
|
644 | Marc Lehmann <schmorp@schmorp.de> |
|
|
645 | http://home.schmorp.de/ |
|
|
646 | |
|
|
647 | POD ERRORS |
|
|
648 | Hey! The above document had some coding errors, which are explained |
|
|
649 | below: |
|
|
650 | |
|
|
651 | Around line 360: |
|
|
652 | You can't have =items (as at line 476) unless the first thing after |
|
|
653 | the =over is an =item |
|
|
654 | |