ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-Fork/Fork.pm
Revision: 1.63
Committed: Wed Nov 26 13:36:18 2014 UTC (9 years, 7 months ago) by root
Branch: MAIN
Changes since 1.62: +43 -13 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 AnyEvent::Fork - everything you wanted to use fork() for, but couldn't
4
5 =head1 SYNOPSIS
6
7 use AnyEvent::Fork;
8
9 AnyEvent::Fork
10 ->new
11 ->require ("MyModule")
12 ->run ("MyModule::server", my $cv = AE::cv);
13
14 my $fh = $cv->recv;
15
16 =head1 DESCRIPTION
17
18 This module allows you to create new processes, without actually forking
19 them from your current process (avoiding the problems of forking), but
20 preserving most of the advantages of fork.
21
22 It can be used to create new worker processes or new independent
23 subprocesses for short- and long-running jobs, process pools (e.g. for use
24 in pre-forked servers) but also to spawn new external processes (such as
25 CGI scripts from a web server), which can be faster (and more well behaved)
26 than using fork+exec in big processes.
27
28 Special care has been taken to make this module useful from other modules,
29 while still supporting specialised environments such as L<App::Staticperl>
30 or L<PAR::Packer>.
31
32 =head2 WHAT THIS MODULE IS NOT
33
34 This module only creates processes and lets you pass file handles and
35 strings to it, and run perl code. It does not implement any kind of RPC -
36 there is no back channel from the process back to you, and there is no RPC
37 or message passing going on.
38
39 If you need some form of RPC, you could use the L<AnyEvent::Fork::RPC>
40 companion module, which adds simple RPC/job queueing to a process created
41 by this module.
42
43 And if you need some automatic process pool management on top of
44 L<AnyEvent::Fork::RPC>, you can look at the L<AnyEvent::Fork::Pool>
45 companion module.
46
47 Or you can implement it yourself in whatever way you like: use some
48 message-passing module such as L<AnyEvent::MP>, some pipe such as
49 L<AnyEvent::ZeroMQ>, use L<AnyEvent::Handle> on both sides to send
50 e.g. JSON or Storable messages, and so on.
51
52 =head2 COMPARISON TO OTHER MODULES
53
54 There is an abundance of modules on CPAN that do "something fork", such as
55 L<Parallel::ForkManager>, L<AnyEvent::ForkManager>, L<AnyEvent::Worker>
56 or L<AnyEvent::Subprocess>. There are modules that implement their own
57 process management, such as L<AnyEvent::DBI>.
58
59 The problems that all these modules try to solve are real, however, none
60 of them (from what I have seen) tackle the very real problems of unwanted
61 memory sharing, efficiency or not being able to use event processing, GUI
62 toolkits or similar modules in the processes they create.
63
64 This module doesn't try to replace any of them - instead it tries to solve
65 the problem of creating processes with a minimum of fuss and overhead (and
66 also luxury). Ideally, most of these would use AnyEvent::Fork internally,
67 except they were written before AnyEvent:Fork was available, so obviously
68 had to roll their own.
69
70 =head2 PROBLEM STATEMENT
71
72 There are two traditional ways to implement parallel processing on UNIX
73 like operating systems - fork and process, and fork+exec and process. They
74 have different advantages and disadvantages that I describe below,
75 together with how this module tries to mitigate the disadvantages.
76
77 =over 4
78
79 =item Forking from a big process can be very slow.
80
81 A 5GB process needs 0.05s to fork on my 3.6GHz amd64 GNU/Linux box. This
82 overhead is often shared with exec (because you have to fork first), but
83 in some circumstances (e.g. when vfork is used), fork+exec can be much
84 faster.
85
86 This module can help here by telling a small(er) helper process to fork,
87 which is faster then forking the main process, and also uses vfork where
88 possible. This gives the speed of vfork, with the flexibility of fork.
89
90 =item Forking usually creates a copy-on-write copy of the parent
91 process.
92
93 For example, modules or data files that are loaded will not use additional
94 memory after a fork. Exec'ing a new process, in contrast, means modules
95 and data files might need to be loaded again, at extra CPU and memory
96 cost.
97
98 But when forking, you still create a copy of your data structures - if
99 the program frees them and replaces them by new data, the child processes
100 will retain the old version even if it isn't used, which can suddenly and
101 unexpectedly increase memory usage when freeing memory.
102
103 For example, L<Gtk2::CV> is an image viewer optimised for large
104 directories (millions of pictures). It also forks subprocesses for
105 thumbnail generation, which inherit the data structure that stores all
106 file information. If the user changes the directory, it gets freed in
107 the main process, leaving a copy in the thumbnailer processes. This can
108 lead to many times the memory usage that would actually be required. The
109 solution is to fork early (and being unable to dynamically generate more
110 subprocesses or do this from a module)... or to use L<AnyEvent:Fork>.
111
112 There is a trade-off between more sharing with fork (which can be good or
113 bad), and no sharing with exec.
114
115 This module allows the main program to do a controlled fork, and allows
116 modules to exec processes safely at any time. When creating a custom
117 process pool you can take advantage of data sharing via fork without
118 risking to share large dynamic data structures that will blow up child
119 memory usage.
120
121 In other words, this module puts you into control over what is being
122 shared and what isn't, at all times.
123
124 =item Exec'ing a new perl process might be difficult.
125
126 For example, it is not easy to find the correct path to the perl
127 interpreter - C<$^X> might not be a perl interpreter at all. Worse, there
128 might not even be a perl binary installed on the system.
129
130 This module tries hard to identify the correct path to the perl
131 interpreter. With a cooperative main program, exec'ing the interpreter
132 might not even be necessary, but even without help from the main program,
133 it will still work when used from a module.
134
135 =item Exec'ing a new perl process might be slow, as all necessary modules
136 have to be loaded from disk again, with no guarantees of success.
137
138 Long running processes might run into problems when perl is upgraded
139 and modules are no longer loadable because they refer to a different
140 perl version, or parts of a distribution are newer than the ones already
141 loaded.
142
143 This module supports creating pre-initialised perl processes to be used as
144 a template for new processes at a later time, e.g. for use in a process
145 pool.
146
147 =item Forking might be impossible when a program is running.
148
149 For example, POSIX makes it almost impossible to fork from a
150 multi-threaded program while doing anything useful in the child - in
151 fact, if your perl program uses POSIX threads (even indirectly via
152 e.g. L<IO::AIO> or L<threads>), you cannot call fork on the perl level
153 anymore without risking memory corruption or worse on a number of
154 operating systems.
155
156 This module can safely fork helper processes at any time, by calling
157 fork+exec in C, in a POSIX-compatible way (via L<Proc::FastSpawn>).
158
159 =item Parallel processing with fork might be inconvenient or difficult
160 to implement. Modules might not work in both parent and child.
161
162 For example, when a program uses an event loop and creates watchers it
163 becomes very hard to use the event loop from a child program, as the
164 watchers already exist but are only meaningful in the parent. Worse, a
165 module might want to use such a module, not knowing whether another module
166 or the main program also does, leading to problems.
167
168 Apart from event loops, graphical toolkits also commonly fall into the
169 "unsafe module" category, or just about anything that communicates with
170 the external world, such as network libraries and file I/O modules, which
171 usually don't like being copied and then allowed to continue in two
172 processes.
173
174 With this module only the main program is allowed to create new processes
175 by forking (because only the main program can know when it is still safe
176 to do so) - all other processes are created via fork+exec, which makes it
177 possible to use modules such as event loops or window interfaces safely.
178
179 =back
180
181 =head1 EXAMPLES
182
183 =head2 Create a single new process, tell it to run your worker function.
184
185 AnyEvent::Fork
186 ->new
187 ->require ("MyModule")
188 ->run ("MyModule::worker, sub {
189 my ($master_filehandle) = @_;
190
191 # now $master_filehandle is connected to the
192 # $slave_filehandle in the new process.
193 });
194
195 C<MyModule> might look like this:
196
197 package MyModule;
198
199 sub worker {
200 my ($slave_filehandle) = @_;
201
202 # now $slave_filehandle is connected to the $master_filehandle
203 # in the original prorcess. have fun!
204 }
205
206 =head2 Create a pool of server processes all accepting on the same socket.
207
208 # create listener socket
209 my $listener = ...;
210
211 # create a pool template, initialise it and give it the socket
212 my $pool = AnyEvent::Fork
213 ->new
214 ->require ("Some::Stuff", "My::Server")
215 ->send_fh ($listener);
216
217 # now create 10 identical workers
218 for my $id (1..10) {
219 $pool
220 ->fork
221 ->send_arg ($id)
222 ->run ("My::Server::run");
223 }
224
225 # now do other things - maybe use the filehandle provided by run
226 # to wait for the processes to die. or whatever.
227
228 C<My::Server> might look like this:
229
230 package My::Server;
231
232 sub run {
233 my ($slave, $listener, $id) = @_;
234
235 close $slave; # we do not use the socket, so close it to save resources
236
237 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
238 # or anything we usually couldn't do in a process forked normally.
239 while (my $socket = $listener->accept) {
240 # do sth. with new socket
241 }
242 }
243
244 =head2 use AnyEvent::Fork as a faster fork+exec
245
246 This runs C</bin/echo hi>, with standard output redirected to F</tmp/log>
247 and standard error redirected to the communications socket. It is usually
248 faster than fork+exec, but still lets you prepare the environment.
249
250 open my $output, ">/tmp/log" or die "$!";
251
252 AnyEvent::Fork
253 ->new
254 ->eval ('
255 # compile a helper function for later use
256 sub run {
257 my ($fh, $output, @cmd) = @_;
258
259 # perl will clear close-on-exec on STDOUT/STDERR
260 open STDOUT, ">&", $output or die;
261 open STDERR, ">&", $fh or die;
262
263 exec @cmd;
264 }
265 ')
266 ->send_fh ($output)
267 ->send_arg ("/bin/echo", "hi")
268 ->run ("run", my $cv = AE::cv);
269
270 my $stderr = $cv->recv;
271
272 =head2 For stingy users: put the worker code into a C<DATA> section.
273
274 When you want to be stingy with files, you can put your code into the
275 C<DATA> section of your module (or program):
276
277 use AnyEvent::Fork;
278
279 AnyEvent::Fork
280 ->new
281 ->eval (do { local $/; <DATA> })
282 ->run ("doit", sub { ... });
283
284 __DATA__
285
286 sub doit {
287 ... do something!
288 }
289
290 =head2 For stingy standalone programs: do not rely on external files at
291 all.
292
293 For single-file scripts it can be inconvenient to rely on external
294 files - even when using a C<DATA> section, you still need to C<exec> an
295 external perl interpreter, which might not be available when using
296 L<App::Staticperl>, L<Urlader> or L<PAR::Packer> for example.
297
298 Two modules help here - L<AnyEvent::Fork::Early> forks a template process
299 for all further calls to C<new_exec>, and L<AnyEvent::Fork::Template>
300 forks the main program as a template process.
301
302 Here is how your main program should look like:
303
304 #! perl
305
306 # optional, as the very first thing.
307 # in case modules want to create their own processes.
308 use AnyEvent::Fork::Early;
309
310 # next, load all modules you need in your template process
311 use Example::My::Module
312 use Example::Whatever;
313
314 # next, put your run function definition and anything else you
315 # need, but do not use code outside of BEGIN blocks.
316 sub worker_run {
317 my ($fh, @args) = @_;
318 ...
319 }
320
321 # now preserve everything so far as AnyEvent::Fork object
322 # in $TEMPLATE.
323 use AnyEvent::Fork::Template;
324
325 # do not put code outside of BEGIN blocks until here
326
327 # now use the $TEMPLATE process in any way you like
328
329 # for example: create 10 worker processes
330 my @worker;
331 my $cv = AE::cv;
332 for (1..10) {
333 $cv->begin;
334 $TEMPLATE->fork->send_arg ($_)->run ("worker_run", sub {
335 push @worker, shift;
336 $cv->end;
337 });
338 }
339 $cv->recv;
340
341 =head1 CONCEPTS
342
343 This module can create new processes either by executing a new perl
344 process, or by forking from an existing "template" process.
345
346 All these processes are called "child processes" (whether they are direct
347 children or not), while the process that manages them is called the
348 "parent process".
349
350 Each such process comes with its own file handle that can be used to
351 communicate with it (it's actually a socket - one end in the new process,
352 one end in the main process), and among the things you can do in it are
353 load modules, fork new processes, send file handles to it, and execute
354 functions.
355
356 There are multiple ways to create additional processes to execute some
357 jobs:
358
359 =over 4
360
361 =item fork a new process from the "default" template process, load code,
362 run it
363
364 This module has a "default" template process which it executes when it is
365 needed the first time. Forking from this process shares the memory used
366 for the perl interpreter with the new process, but loading modules takes
367 time, and the memory is not shared with anything else.
368
369 This is ideal for when you only need one extra process of a kind, with the
370 option of starting and stopping it on demand.
371
372 Example:
373
374 AnyEvent::Fork
375 ->new
376 ->require ("Some::Module")
377 ->run ("Some::Module::run", sub {
378 my ($fork_fh) = @_;
379 });
380
381 =item fork a new template process, load code, then fork processes off of
382 it and run the code
383
384 When you need to have a bunch of processes that all execute the same (or
385 very similar) tasks, then a good way is to create a new template process
386 for them, loading all the modules you need, and then create your worker
387 processes from this new template process.
388
389 This way, all code (and data structures) that can be shared (e.g. the
390 modules you loaded) is shared between the processes, and each new process
391 consumes relatively little memory of its own.
392
393 The disadvantage of this approach is that you need to create a template
394 process for the sole purpose of forking new processes from it, but if you
395 only need a fixed number of processes you can create them, and then destroy
396 the template process.
397
398 Example:
399
400 my $template = AnyEvent::Fork->new->require ("Some::Module");
401
402 for (1..10) {
403 $template->fork->run ("Some::Module::run", sub {
404 my ($fork_fh) = @_;
405 });
406 }
407
408 # at this point, you can keep $template around to fork new processes
409 # later, or you can destroy it, which causes it to vanish.
410
411 =item execute a new perl interpreter, load some code, run it
412
413 This is relatively slow, and doesn't allow you to share memory between
414 multiple processes.
415
416 The only advantage is that you don't have to have a template process
417 hanging around all the time to fork off some new processes, which might be
418 an advantage when there are long time spans where no extra processes are
419 needed.
420
421 Example:
422
423 AnyEvent::Fork
424 ->new_exec
425 ->require ("Some::Module")
426 ->run ("Some::Module::run", sub {
427 my ($fork_fh) = @_;
428 });
429
430 =back
431
432 =head1 THE C<AnyEvent::Fork> CLASS
433
434 This module exports nothing, and only implements a single class -
435 C<AnyEvent::Fork>.
436
437 There are two class constructors that both create new processes - C<new>
438 and C<new_exec>. The C<fork> method creates a new process by forking an
439 existing one and could be considered a third constructor.
440
441 Most of the remaining methods deal with preparing the new process, by
442 loading code, evaluating code and sending data to the new process. They
443 usually return the process object, so you can chain method calls.
444
445 If a process object is destroyed before calling its C<run> method, then
446 the process simply exits. After C<run> is called, all responsibility is
447 passed to the specified function.
448
449 As long as there is any outstanding work to be done, process objects
450 resist being destroyed, so there is no reason to store them unless you
451 need them later - configure and forget works just fine.
452
453 =over 4
454
455 =cut
456
457 package AnyEvent::Fork;
458
459 use common::sense;
460
461 use Errno ();
462
463 use AnyEvent;
464 use AnyEvent::Util ();
465
466 use IO::FDPass;
467
468 our $VERSION = 1.2;
469
470 # the early fork template process
471 our $EARLY;
472
473 # the empty template process
474 our $TEMPLATE;
475
476 sub QUEUE() { 0 }
477 sub FH() { 1 }
478 sub WW() { 2 }
479 sub PID() { 3 }
480 sub CB() { 4 }
481
482 sub _new {
483 my ($self, $fh, $pid) = @_;
484
485 AnyEvent::Util::fh_nonblocking $fh, 1;
486
487 $self = bless [
488 [], # write queue - strings or fd's
489 $fh,
490 undef, # AE watcher
491 $pid,
492 ], $self;
493
494 $self
495 }
496
497 sub _cmd {
498 my $self = shift;
499
500 # ideally, we would want to use "a (w/a)*" as format string, but perl
501 # versions from at least 5.8.9 to 5.16.3 are all buggy and can't unpack
502 # it.
503 push @{ $self->[QUEUE] }, pack "a L/a*", $_[0], $_[1];
504
505 $self->[WW] ||= AE::io $self->[FH], 1, sub {
506 do {
507 # send the next "thing" in the queue - either a reference to an fh,
508 # or a plain string.
509
510 if (ref $self->[QUEUE][0]) {
511 # send fh
512 unless (IO::FDPass::send fileno $self->[FH], fileno ${ $self->[QUEUE][0] }) {
513 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK;
514 undef $self->[WW];
515 die "AnyEvent::Fork: file descriptor send failure: $!";
516 }
517
518 shift @{ $self->[QUEUE] };
519
520 } else {
521 # send string
522 my $len = syswrite $self->[FH], $self->[QUEUE][0];
523
524 unless ($len) {
525 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK;
526 undef $self->[WW];
527 die "AnyEvent::Fork: command write failure: $!";
528 }
529
530 substr $self->[QUEUE][0], 0, $len, "";
531 shift @{ $self->[QUEUE] } unless length $self->[QUEUE][0];
532 }
533 } while @{ $self->[QUEUE] };
534
535 # everything written
536 undef $self->[WW];
537
538 # invoke run callback, if any
539 if ($self->[CB]) {
540 $self->[CB]->($self->[FH]);
541 @$self = ();
542 }
543 };
544
545 () # make sure we don't leak the watcher
546 }
547
548 # fork template from current process, used by AnyEvent::Fork::Early/Template
549 sub _new_fork {
550 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
551 my $parent = $$;
552
553 my $pid = fork;
554
555 if ($pid eq 0) {
556 require AnyEvent::Fork::Serve;
557 $AnyEvent::Fork::Serve::OWNER = $parent;
558 close $fh;
559 $0 = "$_[1] of $parent";
560 AnyEvent::Fork::Serve::serve ($slave);
561 exit 0;
562 } elsif (!$pid) {
563 die "AnyEvent::Fork::Early/Template: unable to fork template process: $!";
564 }
565
566 AnyEvent::Fork->_new ($fh, $pid)
567 }
568
569 =item my $proc = new AnyEvent::Fork
570
571 Create a new "empty" perl interpreter process and returns its process
572 object for further manipulation.
573
574 The new process is forked from a template process that is kept around
575 for this purpose. When it doesn't exist yet, it is created by a call to
576 C<new_exec> first and then stays around for future calls.
577
578 =cut
579
580 sub new {
581 my $class = shift;
582
583 $TEMPLATE ||= $class->new_exec;
584 $TEMPLATE->fork
585 }
586
587 =item $new_proc = $proc->fork
588
589 Forks C<$proc>, creating a new process, and returns the process object
590 of the new process.
591
592 If any of the C<send_> functions have been called before fork, then they
593 will be cloned in the child. For example, in a pre-forked server, you
594 might C<send_fh> the listening socket into the template process, and then
595 keep calling C<fork> and C<run>.
596
597 =cut
598
599 sub fork {
600 my ($self) = @_;
601
602 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
603
604 $self->send_fh ($slave);
605 $self->_cmd ("f");
606
607 AnyEvent::Fork->_new ($fh)
608 }
609
610 =item my $proc = new_exec AnyEvent::Fork
611
612 Create a new "empty" perl interpreter process and returns its process
613 object for further manipulation.
614
615 Unlike the C<new> method, this method I<always> spawns a new perl process
616 (except in some cases, see L<AnyEvent::Fork::Early> for details). This
617 reduces the amount of memory sharing that is possible, and is also slower.
618
619 You should use C<new> whenever possible, except when having a template
620 process around is unacceptable.
621
622 The path to the perl interpreter is divined using various methods - first
623 C<$^X> is investigated to see if the path ends with something that looks
624 as if it were the perl interpreter. Failing this, the module falls back to
625 using C<$Config::Config{perlpath}>.
626
627 The path to perl can also be overriden by setting the global variable
628 C<$AnyEvent::Fork::PERL> - it's value will be used for all subsequent
629 invocations.
630
631 =cut
632
633 our $PERL;
634
635 sub new_exec {
636 my ($self) = @_;
637
638 return $EARLY->fork
639 if $EARLY;
640
641 unless (defined $PERL) {
642 # first find path of perl
643 my $perl = $^X;
644
645 # first we try $^X, but the path must be absolute (always on win32), and end in sth.
646 # that looks like perl. this obviously only works for posix and win32
647 unless (
648 ($^O eq "MSWin32" || $perl =~ m%^/%)
649 && $perl =~ m%[/\\]perl(?:[0-9]+(\.[0-9]+)+)?(\.exe)?$%i
650 ) {
651 # if it doesn't look perlish enough, try Config
652 require Config;
653 $perl = $Config::Config{perlpath};
654 $perl =~ s/(?:\Q$Config::Config{_exe}\E)?$/$Config::Config{_exe}/;
655 }
656
657 $PERL = $perl;
658 }
659
660 require Proc::FastSpawn;
661
662 my ($fh, $slave) = AnyEvent::Util::portable_socketpair;
663 Proc::FastSpawn::fd_inherit (fileno $slave);
664
665 # new fh's should always be set cloexec (due to $^F),
666 # but hey, not on win32, so we always clear the inherit flag.
667 Proc::FastSpawn::fd_inherit (fileno $fh, 0);
668
669 # quick. also doesn't work in win32. of course. what did you expect
670 #local $ENV{PERL5LIB} = join ":", grep !ref, @INC;
671 my %env = %ENV;
672 $env{PERL5LIB} = join +($^O eq "MSWin32" ? ";" : ":"), grep !ref, @INC;
673
674 my $pid = Proc::FastSpawn::spawn (
675 $PERL,
676 ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$],
677 [map "$_=$env{$_}", keys %env],
678 ) or die "unable to spawn AnyEvent::Fork server: $!";
679
680 $self->_new ($fh, $pid)
681 }
682
683 =item $pid = $proc->pid
684
685 Returns the process id of the process I<iff it is a direct child of the
686 process running AnyEvent::Fork>, and C<undef> otherwise. As a general
687 rule (that you cannot rely upon), processes created via C<new_exec>,
688 L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template> are direct
689 children, while all other processes are not.
690
691 Or in other words, you do not normally have to take care of zombies for
692 processes created via C<new>, but when in doubt, or zombies are a problem,
693 you need to check whether a process is a diretc child by calling this
694 method, and possibly creating a child watcher or reap it manually.
695
696 =cut
697
698 sub pid {
699 $_[0][PID]
700 }
701
702 =item $proc = $proc->eval ($perlcode, @args)
703
704 Evaluates the given C<$perlcode> as ... Perl code, while setting C<@_> to
705 the strings specified by C<@args>, in the "main" package.
706
707 This call is meant to do any custom initialisation that might be required
708 (for example, the C<require> method uses it). It's not supposed to be used
709 to completely take over the process, use C<run> for that.
710
711 The code will usually be executed after this call returns, and there is no
712 way to pass anything back to the calling process. Any evaluation errors
713 will be reported to stderr and cause the process to exit.
714
715 If you want to execute some code (that isn't in a module) to take over the
716 process, you should compile a function via C<eval> first, and then call
717 it via C<run>. This also gives you access to any arguments passed via the
718 C<send_xxx> methods, such as file handles. See the L<use AnyEvent::Fork as
719 a faster fork+exec> example to see it in action.
720
721 Returns the process object for easy chaining of method calls.
722
723 =cut
724
725 sub eval {
726 my ($self, $code, @args) = @_;
727
728 $self->_cmd (e => pack "(w/a*)*", $code, @args);
729
730 $self
731 }
732
733 =item $proc = $proc->require ($module, ...)
734
735 Tries to load the given module(s) into the process
736
737 Returns the process object for easy chaining of method calls.
738
739 =cut
740
741 sub require {
742 my ($self, @modules) = @_;
743
744 s%::%/%g for @modules;
745 $self->eval ('require "$_.pm" for @_', @modules);
746
747 $self
748 }
749
750 =item $proc = $proc->send_fh ($handle, ...)
751
752 Send one or more file handles (I<not> file descriptors) to the process,
753 to prepare a call to C<run>.
754
755 The process object keeps a reference to the handles until they have
756 been passed over to the process, so you must not explicitly close the
757 handles. This is most easily accomplished by simply not storing the file
758 handles anywhere after passing them to this method - when AnyEvent::Fork
759 is finished using them, perl will automatically close them.
760
761 Returns the process object for easy chaining of method calls.
762
763 Example: pass a file handle to a process, and release it without
764 closing. It will be closed automatically when it is no longer used.
765
766 $proc->send_fh ($my_fh);
767 undef $my_fh; # free the reference if you want, but DO NOT CLOSE IT
768
769 =cut
770
771 sub send_fh {
772 my ($self, @fh) = @_;
773
774 for my $fh (@fh) {
775 $self->_cmd ("h");
776 push @{ $self->[QUEUE] }, \$fh;
777 }
778
779 $self
780 }
781
782 =item $proc = $proc->send_arg ($string, ...)
783
784 Send one or more argument strings to the process, to prepare a call to
785 C<run>. The strings can be any octet strings.
786
787 The protocol is optimised to pass a moderate number of relatively short
788 strings - while you can pass up to 4GB of data in one go, this is more
789 meant to pass some ID information or other startup info, not big chunks of
790 data.
791
792 Returns the process object for easy chaining of method calls.
793
794 =cut
795
796 sub send_arg {
797 my ($self, @arg) = @_;
798
799 $self->_cmd (a => pack "(w/a*)*", @arg);
800
801 $self
802 }
803
804 =item $proc->run ($func, $cb->($fh))
805
806 Enter the function specified by the function name in C<$func> in the
807 process. The function is called with the communication socket as first
808 argument, followed by all file handles and string arguments sent earlier
809 via C<send_fh> and C<send_arg> methods, in the order they were called.
810
811 The process object becomes unusable on return from this function - any
812 further method calls result in undefined behaviour.
813
814 The function name should be fully qualified, but if it isn't, it will be
815 looked up in the C<main> package.
816
817 If the called function returns, doesn't exist, or any error occurs, the
818 process exits.
819
820 Preparing the process is done in the background - when all commands have
821 been sent, the callback is invoked with the local communications socket
822 as argument. At this point you can start using the socket in any way you
823 like.
824
825 If the communication socket isn't used, it should be closed on both sides,
826 to save on kernel memory.
827
828 The socket is non-blocking in the parent, and blocking in the newly
829 created process. The close-on-exec flag is set in both.
830
831 Even if not used otherwise, the socket can be a good indicator for the
832 existence of the process - if the other process exits, you get a readable
833 event on it, because exiting the process closes the socket (if it didn't
834 create any children using fork).
835
836 =over 4
837
838 =item Compatibility to L<AnyEvent::Fork::Remote>
839
840 If you want to write code that works with both this module and
841 L<AnyEvent::Fork::Remote>, you need to write your code so that it assumes
842 there are two file handles for communications, which might not be unix
843 domain sockets. The C<run> function should start like this:
844
845 sub run {
846 my ($rfh, @args) = @_; # @args is your normal arguments
847 my $wfh = fileno $rfh ? $rfh : *STDOUT;
848
849 # now use $rfh for reading and $wfh for writing
850 }
851
852 This checks whether the passed file handle is, in fact, the process
853 C<STDIN> handle. If it is, then the function was invoked visa
854 L<AnyEvent::Fork::Remote>, so STDIN should be used for reading and
855 C<STDOUT> should be used for writing.
856
857 In all other cases, the function was called via this module, and there is
858 only one file handle that should be sued for reading and writing.
859
860 =back
861
862 Example: create a template for a process pool, pass a few strings, some
863 file handles, then fork, pass one more string, and run some code.
864
865 my $pool = AnyEvent::Fork
866 ->new
867 ->send_arg ("str1", "str2")
868 ->send_fh ($fh1, $fh2);
869
870 for (1..2) {
871 $pool
872 ->fork
873 ->send_arg ("str3")
874 ->run ("Some::function", sub {
875 my ($fh) = @_;
876
877 # fh is nonblocking, but we trust that the OS can accept these
878 # few octets anyway.
879 syswrite $fh, "hi #$_\n";
880
881 # $fh is being closed here, as we don't store it anywhere
882 });
883 }
884
885 # Some::function might look like this - all parameters passed before fork
886 # and after will be passed, in order, after the communications socket.
887 sub Some::function {
888 my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_;
889
890 print scalar <$fh>; # prints "hi #1\n" and "hi #2\n" in any order
891 }
892
893 =cut
894
895 sub run {
896 my ($self, $func, $cb) = @_;
897
898 $self->[CB] = $cb;
899 $self->_cmd (r => $func);
900 }
901
902 =back
903
904 =head2 EXPERIMENTAL METHODS
905
906 These methods might go away completely or change behaviour, at any time.
907
908 =over 4
909
910 =item $proc->to_fh ($cb->($fh)) # EXPERIMENTAL, MIGHT BE REMOVED
911
912 Flushes all commands out to the process and then calls the callback with
913 the communications socket.
914
915 The process object becomes unusable on return from this function - any
916 further method calls result in undefined behaviour.
917
918 The point of this method is to give you a file handle that you can pass
919 to another process. In that other process, you can call C<new_from_fh
920 AnyEvent::Fork $fh> to create a new C<AnyEvent::Fork> object from it,
921 thereby effectively passing a fork object to another process.
922
923 =cut
924
925 sub to_fh {
926 my ($self, $cb) = @_;
927
928 $self->[CB] = $cb;
929
930 unless ($self->[WW]) {
931 $self->[CB]->($self->[FH]);
932 @$self = ();
933 }
934 }
935
936 =item new_from_fh AnyEvent::Fork $fh # EXPERIMENTAL, MIGHT BE REMOVED
937
938 Takes a file handle originally rceeived by the C<to_fh> method and creates
939 a new C<AnyEvent:Fork> object. The child process itself will not change in
940 any way, i.e. it will keep all the modifications done to it before calling
941 C<to_fh>.
942
943 The new object is very much like the original object, except that the
944 C<pid> method will return C<undef> even if the process is a direct child.
945
946 =cut
947
948 sub new_from_fh {
949 my ($class, $fh) = @_;
950
951 $class->_new ($fh)
952 }
953
954 =back
955
956 =head1 PERFORMANCE
957
958 Now for some unscientific benchmark numbers (all done on an amd64
959 GNU/Linux box). These are intended to give you an idea of the relative
960 performance you can expect, they are not meant to be absolute performance
961 numbers.
962
963 OK, so, I ran a simple benchmark that creates a socket pair, forks, calls
964 exit in the child and waits for the socket to close in the parent. I did
965 load AnyEvent, EV and AnyEvent::Fork, for a total process size of 5100kB.
966
967 2079 new processes per second, using manual socketpair + fork
968
969 Then I did the same thing, but instead of calling fork, I called
970 AnyEvent::Fork->new->run ("CORE::exit") and then again waited for the
971 socket from the child to close on exit. This does the same thing as manual
972 socket pair + fork, except that what is forked is the template process
973 (2440kB), and the socket needs to be passed to the server at the other end
974 of the socket first.
975
976 2307 new processes per second, using AnyEvent::Fork->new
977
978 And finally, using C<new_exec> instead C<new>, using vforks+execs to exec
979 a new perl interpreter and compile the small server each time, I get:
980
981 479 vfork+execs per second, using AnyEvent::Fork->new_exec
982
983 So how can C<< AnyEvent->new >> be faster than a standard fork, even
984 though it uses the same operations, but adds a lot of overhead?
985
986 The difference is simply the process size: forking the 5MB process takes
987 so much longer than forking the 2.5MB template process that the extra
988 overhead is canceled out.
989
990 If the benchmark process grows, the normal fork becomes even slower:
991
992 1340 new processes, manual fork of a 20MB process
993 731 new processes, manual fork of a 200MB process
994 235 new processes, manual fork of a 2000MB process
995
996 What that means (to me) is that I can use this module without having a bad
997 conscience because of the extra overhead required to start new processes.
998
999 =head1 TYPICAL PROBLEMS
1000
1001 This section lists typical problems that remain. I hope by recognising
1002 them, most can be avoided.
1003
1004 =over 4
1005
1006 =item leaked file descriptors for exec'ed processes
1007
1008 POSIX systems inherit file descriptors by default when exec'ing a new
1009 process. While perl itself laudably sets the close-on-exec flags on new
1010 file handles, most C libraries don't care, and even if all cared, it's
1011 often not possible to set the flag in a race-free manner.
1012
1013 That means some file descriptors can leak through. And since it isn't
1014 possible to know which file descriptors are "good" and "necessary" (or
1015 even to know which file descriptors are open), there is no good way to
1016 close the ones that might harm.
1017
1018 As an example of what "harm" can be done consider a web server that
1019 accepts connections and afterwards some module uses AnyEvent::Fork for the
1020 first time, causing it to fork and exec a new process, which might inherit
1021 the network socket. When the server closes the socket, it is still open
1022 in the child (which doesn't even know that) and the client might conclude
1023 that the connection is still fine.
1024
1025 For the main program, there are multiple remedies available -
1026 L<AnyEvent::Fork::Early> is one, creating a process early and not using
1027 C<new_exec> is another, as in both cases, the first process can be exec'ed
1028 well before many random file descriptors are open.
1029
1030 In general, the solution for these kind of problems is to fix the
1031 libraries or the code that leaks those file descriptors.
1032
1033 Fortunately, most of these leaked descriptors do no harm, other than
1034 sitting on some resources.
1035
1036 =item leaked file descriptors for fork'ed processes
1037
1038 Normally, L<AnyEvent::Fork> does start new processes by exec'ing them,
1039 which closes file descriptors not marked for being inherited.
1040
1041 However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer
1042 a way to create these processes by forking, and this leaks more file
1043 descriptors than exec'ing them, as there is no way to mark descriptors as
1044 "close on fork".
1045
1046 An example would be modules like L<EV>, L<IO::AIO> or L<Gtk2>. Both create
1047 pipes for internal uses, and L<Gtk2> might open a connection to the X
1048 server. L<EV> and L<IO::AIO> can deal with fork, but Gtk2 might have
1049 trouble with a fork.
1050
1051 The solution is to either not load these modules before use'ing
1052 L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay
1053 initialising them, for example, by calling C<init Gtk2> manually.
1054
1055 =item exiting calls object destructors
1056
1057 This only applies to users of L<AnyEvent::Fork:Early> and
1058 L<AnyEvent::Fork::Template>, or when initialising code creates objects
1059 that reference external resources.
1060
1061 When a process created by AnyEvent::Fork exits, it might do so by calling
1062 exit, or simply letting perl reach the end of the program. At which point
1063 Perl runs all destructors.
1064
1065 Not all destructors are fork-safe - for example, an object that represents
1066 the connection to an X display might tell the X server to free resources,
1067 which is inconvenient when the "real" object in the parent still needs to
1068 use them.
1069
1070 This is obviously not a problem for L<AnyEvent::Fork::Early>, as you used
1071 it as the very first thing, right?
1072
1073 It is a problem for L<AnyEvent::Fork::Template> though - and the solution
1074 is to not create objects with nontrivial destructors that might have an
1075 effect outside of Perl.
1076
1077 =back
1078
1079 =head1 PORTABILITY NOTES
1080
1081 Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop,
1082 and ::Template is not going to work), and it cost a lot of blood and sweat
1083 to make it so, mostly due to the bloody broken perl that nobody seems to
1084 care about. The fork emulation is a bad joke - I have yet to see something
1085 useful that you can do with it without running into memory corruption
1086 issues or other braindamage. Hrrrr.
1087
1088 Since fork is endlessly broken on win32 perls (it doesn't even remotely
1089 work within it's documented limits) and quite obviously it's not getting
1090 improved any time soon, the best way to proceed on windows would be to
1091 always use C<new_exec> and thus never rely on perl's fork "emulation".
1092
1093 Cygwin perl is not supported at the moment due to some hilarious
1094 shortcomings of its API - see L<IO::FDPoll> for more details. If you never
1095 use C<send_fh> and always use C<new_exec> to create processes, it should
1096 work though.
1097
1098 =head1 USING AnyEvent::Fork IN SUBPROCESSES
1099
1100 AnyEvent::Fork itself cannot generally be used in subprocesses. As long as
1101 only one process ever forks new processes, sharing the template processes
1102 is possible (you could use a pipe as a lock by writing a byte into it to
1103 unlock, and reading the byte to lock for example)
1104
1105 To make concurrent calls possible after fork, you should get rid of the
1106 template and early fork processes. AnyEvent::Fork will create a new
1107 template process as needed.
1108
1109 undef $AnyEvent::Fork::EARLY;
1110 undef $AnyEvent::Fork::TEMPLATE;
1111
1112 It doesn't matter whether you get rid of them in the parent or child after
1113 a fork.
1114
1115 =head1 SEE ALSO
1116
1117 L<AnyEvent::Fork::Early>, to avoid executing a perl interpreter at all
1118 (part of this distribution).
1119
1120 L<AnyEvent::Fork::Template>, to create a process by forking the main
1121 program at a convenient time (part of this distribution).
1122
1123 L<AnyEvent::Fork::Remote>, for another way to create processes that is
1124 mostly compatible to this module and modules building on top of it, but
1125 works better with remote processes.
1126
1127 L<AnyEvent::Fork::RPC>, for simple RPC to child processes (on CPAN).
1128
1129 L<AnyEvent::Fork::Pool>, for simple worker process pool (on CPAN).
1130
1131 =head1 AUTHOR AND CONTACT INFORMATION
1132
1133 Marc Lehmann <schmorp@schmorp.de>
1134 http://software.schmorp.de/pkg/AnyEvent-Fork
1135
1136 =cut
1137
1138 1
1139