ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork/Fork.pm
(Generate patch)

Comparing AnyEvent-Fork/Fork.pm (file contents):
Revision 1.26 by root, Sat Apr 6 08:58:51 2013 UTC vs.
Revision 1.39 by root, Sat Apr 6 22:39:37 2013 UTC

27 27
28Special care has been taken to make this module useful from other modules, 28Special care has been taken to make this module useful from other modules,
29while still supporting specialised environments such as L<App::Staticperl> 29while still supporting specialised environments such as L<App::Staticperl>
30or L<PAR::Packer>. 30or L<PAR::Packer>.
31 31
32=head1 WHAT THIS MODULE IS NOT 32=head2 WHAT THIS MODULE IS NOT
33 33
34This module only creates processes and lets you pass file handles and 34This module only creates processes and lets you pass file handles and
35strings to it, and run perl code. It does not implement any kind of RPC - 35strings to it, and run perl code. It does not implement any kind of RPC -
36there is no back channel from the process back to you, and there is no RPC 36there is no back channel from the process back to you, and there is no RPC
37or message passing going on. 37or message passing going on.
40in whatever way you like, use some message-passing module such 40in whatever way you like, use some message-passing module such
41as L<AnyEvent::MP>, some pipe such as L<AnyEvent::ZeroMQ>, use 41as L<AnyEvent::MP>, some pipe such as L<AnyEvent::ZeroMQ>, use
42L<AnyEvent::Handle> on both sides to send e.g. JSON or Storable messages, 42L<AnyEvent::Handle> on both sides to send e.g. JSON or Storable messages,
43and so on. 43and so on.
44 44
45=head2 COMPARISON TO OTHER MODULES
46
47There is an abundance of modules on CPAN that do "something fork", such as
48L<Parallel::ForkManager>, L<AnyEvent::ForkManager>, L<AnyEvent::Worker>
49or L<AnyEvent::Subprocess>. There are modules that implement their own
50process management, such as L<AnyEvent::DBI>.
51
52The problems that all these modules try to solve are real, however, none
53of them (from what I have seen) tackle the very real problems of unwanted
54memory sharing, efficiency, not being able to use event processing or
55similar modules in the processes they create.
56
57This module doesn't try to replace any of them - instead it tries to solve
58the problem of creating processes with a minimum of fuss and overhead (and
59also luxury). Ideally, most of these would use AnyEvent::Fork internally,
60except they were written before AnyEvent:Fork was available, so obviously
61had to roll their own.
62
45=head1 PROBLEM STATEMENT 63=head2 PROBLEM STATEMENT
46 64
47There are two traditional ways to implement parallel processing on UNIX 65There are two traditional ways to implement parallel processing on UNIX
48like operating systems - fork and process, and fork+exec and process. They 66like operating systems - fork and process, and fork+exec and process. They
49have different advantages and disadvantages that I describe below, 67have different advantages and disadvantages that I describe below,
50together with how this module tries to mitigate the disadvantages. 68together with how this module tries to mitigate the disadvantages.
152 170
153 # now $master_filehandle is connected to the 171 # now $master_filehandle is connected to the
154 # $slave_filehandle in the new process. 172 # $slave_filehandle in the new process.
155 }); 173 });
156 174
157 # MyModule::worker might look like this 175C<MyModule> might look like this:
176
177 package MyModule;
178
158 sub MyModule::worker { 179 sub worker {
159 my ($slave_filehandle) = @_; 180 my ($slave_filehandle) = @_;
160 181
161 # now $slave_filehandle is connected to the $master_filehandle 182 # now $slave_filehandle is connected to the $master_filehandle
162 # in the original prorcess. have fun! 183 # in the original prorcess. have fun!
163 } 184 }
182 } 203 }
183 204
184 # now do other things - maybe use the filehandle provided by run 205 # now do other things - maybe use the filehandle provided by run
185 # to wait for the processes to die. or whatever. 206 # to wait for the processes to die. or whatever.
186 207
187 # My::Server::run might look like this 208C<My::Server> might look like this:
188 sub My::Server::run { 209
210 package My::Server;
211
212 sub run {
189 my ($slave, $listener, $id) = @_; 213 my ($slave, $listener, $id) = @_;
190 214
191 close $slave; # we do not use the socket, so close it to save resources 215 close $slave; # we do not use the socket, so close it to save resources
192 216
193 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO, 217 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
197 } 221 }
198 } 222 }
199 223
200=head2 use AnyEvent::Fork as a faster fork+exec 224=head2 use AnyEvent::Fork as a faster fork+exec
201 225
202This runs /bin/echo hi, with stdout redirected to /tmp/log and stderr to 226This runs C</bin/echo hi>, with stdandard output redirected to /tmp/log
203the communications socket. It is usually faster than fork+exec, but still 227and standard error redirected to the communications socket. It is usually
204let's you prepare the environment. 228faster than fork+exec, but still lets you prepare the environment.
205 229
206 open my $output, ">/tmp/log" or die "$!"; 230 open my $output, ">/tmp/log" or die "$!";
207 231
208 AnyEvent::Fork 232 AnyEvent::Fork
209 ->new 233 ->new
309 my ($fork_fh) = @_; 333 my ($fork_fh) = @_;
310 }); 334 });
311 335
312=back 336=back
313 337
314=head1 FUNCTIONS 338=head1 THE C<AnyEvent::Fork> CLASS
339
340This module exports nothing, and only implements a single class -
341C<AnyEvent::Fork>.
342
343There are two class constructors that both create new processes - C<new>
344and C<new_exec>. The C<fork> method creates a new process by forking an
345existing one and could be considered a third constructor.
346
347Most of the remaining methods deal with preparing the new process, by
348loading code, evaluating code and sending data to the new process. They
349usually return the process object, so you can chain method calls.
350
351If a process object is destroyed before calling its C<run> method, then
352the process simply exits. After C<run> is called, all responsibility is
353passed to the specified function.
354
355As long as there is any outstanding work to be done, process objects
356resist being destroyed, so there is no reason to store them unless you
357need them later - configure and forget works just fine.
315 358
316=over 4 359=over 4
317 360
318=cut 361=cut
319 362
329use IO::FDPass; 372use IO::FDPass;
330 373
331our $VERSION = 0.5; 374our $VERSION = 0.5;
332 375
333our $PERL; # the path to the perl interpreter, deduces with various forms of magic 376our $PERL; # the path to the perl interpreter, deduces with various forms of magic
334
335=item my $pool = new AnyEvent::Fork key => value...
336
337Create a new process pool. The following named parameters are supported:
338 377
339=over 4 378=over 4
340 379
341=back 380=back
342 381
438Create a new "empty" perl interpreter process and returns its process 477Create a new "empty" perl interpreter process and returns its process
439object for further manipulation. 478object for further manipulation.
440 479
441The new process is forked from a template process that is kept around 480The new process is forked from a template process that is kept around
442for this purpose. When it doesn't exist yet, it is created by a call to 481for this purpose. When it doesn't exist yet, it is created by a call to
443C<new_exec> and kept around for future calls. 482C<new_exec> first and then stays around for future calls.
444
445When the process object is destroyed, it will release the file handle
446that connects it with the new process. When the new process has not yet
447called C<run>, then the process will exit. Otherwise, what happens depends
448entirely on the code that is executed.
449 483
450=cut 484=cut
451 485
452sub new { 486sub new {
453 my $class = shift; 487 my $class = shift;
543} 577}
544 578
545=item $pid = $proc->pid 579=item $pid = $proc->pid
546 580
547Returns the process id of the process I<iff it is a direct child of the 581Returns the process id of the process I<iff it is a direct child of the
548process> running AnyEvent::Fork, and C<undef> otherwise. 582process running AnyEvent::Fork>, and C<undef> otherwise.
549 583
550Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and 584Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and
551L<AnyEvent::Fork::Template> are direct children, and you are responsible 585L<AnyEvent::Fork::Template> are direct children, and you are responsible
552to clean up their zombies when they die. 586to clean up their zombies when they die.
553 587
554All other processes are not direct children, and will be cleaned up by 588All other processes are not direct children, and will be cleaned up by
555AnyEvent::Fork. 589AnyEvent::Fork itself.
556 590
557=cut 591=cut
558 592
559sub pid { 593sub pid {
560 $_[0][0] 594 $_[0][0]
571 605
572The code will usually be executed after this call returns, and there is no 606The code will usually be executed after this call returns, and there is no
573way to pass anything back to the calling process. Any evaluation errors 607way to pass anything back to the calling process. Any evaluation errors
574will be reported to stderr and cause the process to exit. 608will be reported to stderr and cause the process to exit.
575 609
576If you want to execute some code to take over the process (see the 610If you want to execute some code (that isn't in a module) to take over the
577"fork+exec" example in the SYNOPSIS), you should compile a function via 611process, you should compile a function via C<eval> first, and then call
578C<eval> first, and then call it via C<run>. This also gives you access to 612it via C<run>. This also gives you access to any arguments passed via the
579any arguments passed via the C<send_xxx> methods, such as file handles. 613C<send_xxx> methods, such as file handles. See the L<use AnyEvent::Fork as
614a faster fork+exec> example to see it in action.
580 615
581Returns the process object for easy chaining of method calls. 616Returns the process object for easy chaining of method calls.
582 617
583=cut 618=cut
584 619
610=item $proc = $proc->send_fh ($handle, ...) 645=item $proc = $proc->send_fh ($handle, ...)
611 646
612Send one or more file handles (I<not> file descriptors) to the process, 647Send one or more file handles (I<not> file descriptors) to the process,
613to prepare a call to C<run>. 648to prepare a call to C<run>.
614 649
615The process object keeps a reference to the handles until this is done, 650The process object keeps a reference to the handles until they have
616so you must not explicitly close the handles. This is most easily 651been passed over to the process, so you must not explicitly close the
617accomplished by simply not storing the file handles anywhere after passing 652handles. This is most easily accomplished by simply not storing the file
618them to this method. 653handles anywhere after passing them to this method - when AnyEvent::Fork
654is finished using them, perl will automatically close them.
619 655
620Returns the process object for easy chaining of method calls. 656Returns the process object for easy chaining of method calls.
621 657
622Example: pass a file handle to a process, and release it without 658Example: pass a file handle to a process, and release it without
623closing. It will be closed automatically when it is no longer used. 659closing. It will be closed automatically when it is no longer used.
639} 675}
640 676
641=item $proc = $proc->send_arg ($string, ...) 677=item $proc = $proc->send_arg ($string, ...)
642 678
643Send one or more argument strings to the process, to prepare a call to 679Send one or more argument strings to the process, to prepare a call to
644C<run>. The strings can be any octet string. 680C<run>. The strings can be any octet strings.
645 681
646The protocol is optimised to pass a moderate number of relatively short 682The protocol is optimised to pass a moderate number of relatively short
647strings - while you can pass up to 4GB of data in one go, this is more 683strings - while you can pass up to 4GB of data in one go, this is more
648meant to pass some ID information or other startup info, not big chunks of 684meant to pass some ID information or other startup info, not big chunks of
649data. 685data.
665Enter the function specified by the function name in C<$func> in the 701Enter the function specified by the function name in C<$func> in the
666process. The function is called with the communication socket as first 702process. The function is called with the communication socket as first
667argument, followed by all file handles and string arguments sent earlier 703argument, followed by all file handles and string arguments sent earlier
668via C<send_fh> and C<send_arg> methods, in the order they were called. 704via C<send_fh> and C<send_arg> methods, in the order they were called.
669 705
706The process object becomes unusable on return from this function - any
707further method calls result in undefined behaviour.
708
670The function name should be fully qualified, but if it isn't, it will be 709The function name should be fully qualified, but if it isn't, it will be
671looked up in the main package. 710looked up in the C<main> package.
672 711
673If the called function returns, doesn't exist, or any error occurs, the 712If the called function returns, doesn't exist, or any error occurs, the
674process exits. 713process exits.
675 714
676Preparing the process is done in the background - when all commands have 715Preparing the process is done in the background - when all commands have
677been sent, the callback is invoked with the local communications socket 716been sent, the callback is invoked with the local communications socket
678as argument. At this point you can start using the socket in any way you 717as argument. At this point you can start using the socket in any way you
679like. 718like.
680
681The process object becomes unusable on return from this function - any
682further method calls result in undefined behaviour.
683 719
684If the communication socket isn't used, it should be closed on both sides, 720If the communication socket isn't used, it should be closed on both sides,
685to save on kernel memory. 721to save on kernel memory.
686 722
687The socket is non-blocking in the parent, and blocking in the newly 723The socket is non-blocking in the parent, and blocking in the newly
762 479 vfork+execs per second, using AnyEvent::Fork->new_exec 798 479 vfork+execs per second, using AnyEvent::Fork->new_exec
763 799
764So how can C<< AnyEvent->new >> be faster than a standard fork, even 800So how can C<< AnyEvent->new >> be faster than a standard fork, even
765though it uses the same operations, but adds a lot of overhead? 801though it uses the same operations, but adds a lot of overhead?
766 802
767The difference is simply the process size: forking the 6MB process takes 803The difference is simply the process size: forking the 5MB process takes
768so much longer than forking the 2.5MB template process that the overhead 804so much longer than forking the 2.5MB template process that the extra
769introduced is canceled out. 805overhead introduced is canceled out.
770 806
771If the benchmark process grows, the normal fork becomes even slower: 807If the benchmark process grows, the normal fork becomes even slower:
772 808
773 1340 new processes, manual fork in a 20MB process 809 1340 new processes, manual fork of a 20MB process
774 731 new processes, manual fork in a 200MB process 810 731 new processes, manual fork of a 200MB process
775 235 new processes, manual fork in a 2000MB process 811 235 new processes, manual fork of a 2000MB process
776 812
777What that means (to me) is that I can use this module without having a 813What that means (to me) is that I can use this module without having a bad
778very bad conscience because of the extra overhead required to start new 814conscience because of the extra overhead required to start new processes.
779processes.
780 815
781=head1 TYPICAL PROBLEMS 816=head1 TYPICAL PROBLEMS
782 817
783This section lists typical problems that remain. I hope by recognising 818This section lists typical problems that remain. I hope by recognising
784them, most can be avoided. 819them, most can be avoided.
785 820
786=over 4 821=over 4
787 822
788=item "leaked" file descriptors for exec'ed processes 823=item leaked file descriptors for exec'ed processes
789 824
790POSIX systems inherit file descriptors by default when exec'ing a new 825POSIX systems inherit file descriptors by default when exec'ing a new
791process. While perl itself laudably sets the close-on-exec flags on new 826process. While perl itself laudably sets the close-on-exec flags on new
792file handles, most C libraries don't care, and even if all cared, it's 827file handles, most C libraries don't care, and even if all cared, it's
793often not possible to set the flag in a race-free manner. 828often not possible to set the flag in a race-free manner.
813libraries or the code that leaks those file descriptors. 848libraries or the code that leaks those file descriptors.
814 849
815Fortunately, most of these leaked descriptors do no harm, other than 850Fortunately, most of these leaked descriptors do no harm, other than
816sitting on some resources. 851sitting on some resources.
817 852
818=item "leaked" file descriptors for fork'ed processes 853=item leaked file descriptors for fork'ed processes
819 854
820Normally, L<AnyEvent::Fork> does start new processes by exec'ing them, 855Normally, L<AnyEvent::Fork> does start new processes by exec'ing them,
821which closes file descriptors not marked for being inherited. 856which closes file descriptors not marked for being inherited.
822 857
823However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer 858However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer
832 867
833The solution is to either not load these modules before use'ing 868The solution is to either not load these modules before use'ing
834L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay 869L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay
835initialising them, for example, by calling C<init Gtk2> manually. 870initialising them, for example, by calling C<init Gtk2> manually.
836 871
837=item exit runs destructors 872=item exiting calls object destructors
838 873
839This only applies to users of Lc<AnyEvent::Fork:Early> and 874This only applies to users of L<AnyEvent::Fork:Early> and
840L<AnyEvent::Fork::Template>. 875L<AnyEvent::Fork::Template>, or when initialiasing code creates objects
876that reference external resources.
841 877
842When a process created by AnyEvent::Fork exits, it might do so by calling 878When a process created by AnyEvent::Fork exits, it might do so by calling
843exit, or simply letting perl reach the end of the program. At which point 879exit, or simply letting perl reach the end of the program. At which point
844Perl runs all destructors. 880Perl runs all destructors.
845 881
864to make it so, mostly due to the bloody broken perl that nobody seems to 900to make it so, mostly due to the bloody broken perl that nobody seems to
865care about. The fork emulation is a bad joke - I have yet to see something 901care about. The fork emulation is a bad joke - I have yet to see something
866useful that you can do with it without running into memory corruption 902useful that you can do with it without running into memory corruption
867issues or other braindamage. Hrrrr. 903issues or other braindamage. Hrrrr.
868 904
869Cygwin perl is not supported at the moment, as it should implement fd 905Cygwin perl is not supported at the moment due to some hilarious
870passing, but doesn't, and rolling my own is hard, as cygwin doesn't 906shortcomings of its API - see L<IO::FDPoll> for more details.
871support enough functionality to do it.
872 907
873=head1 SEE ALSO 908=head1 SEE ALSO
874 909
875L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter), 910L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter),
876L<AnyEvent::Fork::Template> (to create a process by forking the main 911L<AnyEvent::Fork::Template> (to create a process by forking the main

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines