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.30 by root, Sat Apr 6 09:28:45 2013 UTC vs.
Revision 1.40 by root, Sat Apr 6 22:41:56 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
157MyModule::worker might look like this: 175C<MyModule> might look like this:
158 176
177 package MyModule;
178
159 sub MyModule::worker { 179 sub worker {
160 my ($slave_filehandle) = @_; 180 my ($slave_filehandle) = @_;
161 181
162 # now $slave_filehandle is connected to the $master_filehandle 182 # now $slave_filehandle is connected to the $master_filehandle
163 # in the original prorcess. have fun! 183 # in the original prorcess. have fun!
164 } 184 }
183 } 203 }
184 204
185 # now do other things - maybe use the filehandle provided by run 205 # now do other things - maybe use the filehandle provided by run
186 # to wait for the processes to die. or whatever. 206 # to wait for the processes to die. or whatever.
187 207
188My::Server::run might look like this: 208C<My::Server> might look like this:
189 209
190 sub My::Server::run { 210 package My::Server;
211
212 sub run {
191 my ($slave, $listener, $id) = @_; 213 my ($slave, $listener, $id) = @_;
192 214
193 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
194 216
195 # 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,
199 } 221 }
200 } 222 }
201 223
202=head2 use AnyEvent::Fork as a faster fork+exec 224=head2 use AnyEvent::Fork as a faster fork+exec
203 225
204This 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
205the communications socket. It is usually faster than fork+exec, but still 227and standard error redirected to the communications socket. It is usually
206let's you prepare the environment. 228faster than fork+exec, but still lets you prepare the environment.
207 229
208 open my $output, ">/tmp/log" or die "$!"; 230 open my $output, ">/tmp/log" or die "$!";
209 231
210 AnyEvent::Fork 232 AnyEvent::Fork
211 ->new 233 ->new
212 ->eval (' 234 ->eval ('
235 # compile a helper function for later use
213 sub run { 236 sub run {
214 my ($fh, $output, @cmd) = @_; 237 my ($fh, $output, @cmd) = @_;
215 238
216 # perl will clear close-on-exec on STDOUT/STDERR 239 # perl will clear close-on-exec on STDOUT/STDERR
217 open STDOUT, ">&", $output or die; 240 open STDOUT, ">&", $output or die;
347use AnyEvent; 370use AnyEvent;
348use AnyEvent::Util (); 371use AnyEvent::Util ();
349 372
350use IO::FDPass; 373use IO::FDPass;
351 374
352our $VERSION = 0.5; 375our $VERSION = 0.6;
353 376
354our $PERL; # the path to the perl interpreter, deduces with various forms of magic 377our $PERL; # the path to the perl interpreter, deduces with various forms of magic
355 378
356=over 4 379=over 4
357 380
555} 578}
556 579
557=item $pid = $proc->pid 580=item $pid = $proc->pid
558 581
559Returns the process id of the process I<iff it is a direct child of the 582Returns the process id of the process I<iff it is a direct child of the
560process> running AnyEvent::Fork, and C<undef> otherwise. 583process running AnyEvent::Fork>, and C<undef> otherwise.
561 584
562Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and 585Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and
563L<AnyEvent::Fork::Template> are direct children, and you are responsible 586L<AnyEvent::Fork::Template> are direct children, and you are responsible
564to clean up their zombies when they die. 587to clean up their zombies when they die.
565 588
583 606
584The code will usually be executed after this call returns, and there is no 607The code will usually be executed after this call returns, and there is no
585way to pass anything back to the calling process. Any evaluation errors 608way to pass anything back to the calling process. Any evaluation errors
586will be reported to stderr and cause the process to exit. 609will be reported to stderr and cause the process to exit.
587 610
588If you want to execute some code to take over the process (see the 611If you want to execute some code (that isn't in a module) to take over the
589"fork+exec" example in the SYNOPSIS), you should compile a function via 612process, you should compile a function via C<eval> first, and then call
590C<eval> first, and then call it via C<run>. This also gives you access to 613it via C<run>. This also gives you access to any arguments passed via the
591any arguments passed via the C<send_xxx> methods, such as file handles. 614C<send_xxx> methods, such as file handles. See the L<use AnyEvent::Fork as
615a faster fork+exec> example to see it in action.
592 616
593Returns the process object for easy chaining of method calls. 617Returns the process object for easy chaining of method calls.
594 618
595=cut 619=cut
596 620
622=item $proc = $proc->send_fh ($handle, ...) 646=item $proc = $proc->send_fh ($handle, ...)
623 647
624Send one or more file handles (I<not> file descriptors) to the process, 648Send one or more file handles (I<not> file descriptors) to the process,
625to prepare a call to C<run>. 649to prepare a call to C<run>.
626 650
627The process object keeps a reference to the handles until this is done, 651The process object keeps a reference to the handles until they have
628so you must not explicitly close the handles. This is most easily 652been passed over to the process, so you must not explicitly close the
629accomplished by simply not storing the file handles anywhere after passing 653handles. This is most easily accomplished by simply not storing the file
630them to this method. 654handles anywhere after passing them to this method - when AnyEvent::Fork
655is finished using them, perl will automatically close them.
631 656
632Returns the process object for easy chaining of method calls. 657Returns the process object for easy chaining of method calls.
633 658
634Example: pass a file handle to a process, and release it without 659Example: pass a file handle to a process, and release it without
635closing. It will be closed automatically when it is no longer used. 660closing. It will be closed automatically when it is no longer used.
651} 676}
652 677
653=item $proc = $proc->send_arg ($string, ...) 678=item $proc = $proc->send_arg ($string, ...)
654 679
655Send one or more argument strings to the process, to prepare a call to 680Send one or more argument strings to the process, to prepare a call to
656C<run>. The strings can be any octet string. 681C<run>. The strings can be any octet strings.
657 682
658The protocol is optimised to pass a moderate number of relatively short 683The protocol is optimised to pass a moderate number of relatively short
659strings - while you can pass up to 4GB of data in one go, this is more 684strings - while you can pass up to 4GB of data in one go, this is more
660meant to pass some ID information or other startup info, not big chunks of 685meant to pass some ID information or other startup info, not big chunks of
661data. 686data.
677Enter the function specified by the function name in C<$func> in the 702Enter the function specified by the function name in C<$func> in the
678process. The function is called with the communication socket as first 703process. The function is called with the communication socket as first
679argument, followed by all file handles and string arguments sent earlier 704argument, followed by all file handles and string arguments sent earlier
680via C<send_fh> and C<send_arg> methods, in the order they were called. 705via C<send_fh> and C<send_arg> methods, in the order they were called.
681 706
707The process object becomes unusable on return from this function - any
708further method calls result in undefined behaviour.
709
682The function name should be fully qualified, but if it isn't, it will be 710The function name should be fully qualified, but if it isn't, it will be
683looked up in the main package. 711looked up in the C<main> package.
684 712
685If the called function returns, doesn't exist, or any error occurs, the 713If the called function returns, doesn't exist, or any error occurs, the
686process exits. 714process exits.
687 715
688Preparing the process is done in the background - when all commands have 716Preparing the process is done in the background - when all commands have
689been sent, the callback is invoked with the local communications socket 717been sent, the callback is invoked with the local communications socket
690as argument. At this point you can start using the socket in any way you 718as argument. At this point you can start using the socket in any way you
691like. 719like.
692
693The process object becomes unusable on return from this function - any
694further method calls result in undefined behaviour.
695 720
696If the communication socket isn't used, it should be closed on both sides, 721If the communication socket isn't used, it should be closed on both sides,
697to save on kernel memory. 722to save on kernel memory.
698 723
699The socket is non-blocking in the parent, and blocking in the newly 724The socket is non-blocking in the parent, and blocking in the newly
774 479 vfork+execs per second, using AnyEvent::Fork->new_exec 799 479 vfork+execs per second, using AnyEvent::Fork->new_exec
775 800
776So how can C<< AnyEvent->new >> be faster than a standard fork, even 801So how can C<< AnyEvent->new >> be faster than a standard fork, even
777though it uses the same operations, but adds a lot of overhead? 802though it uses the same operations, but adds a lot of overhead?
778 803
779The difference is simply the process size: forking the 6MB process takes 804The difference is simply the process size: forking the 5MB process takes
780so much longer than forking the 2.5MB template process that the overhead 805so much longer than forking the 2.5MB template process that the extra
781introduced is canceled out. 806overhead introduced is canceled out.
782 807
783If the benchmark process grows, the normal fork becomes even slower: 808If the benchmark process grows, the normal fork becomes even slower:
784 809
785 1340 new processes, manual fork in a 20MB process 810 1340 new processes, manual fork of a 20MB process
786 731 new processes, manual fork in a 200MB process 811 731 new processes, manual fork of a 200MB process
787 235 new processes, manual fork in a 2000MB process 812 235 new processes, manual fork of a 2000MB process
788 813
789What that means (to me) is that I can use this module without having a 814What that means (to me) is that I can use this module without having a bad
790very bad conscience because of the extra overhead required to start new 815conscience because of the extra overhead required to start new processes.
791processes.
792 816
793=head1 TYPICAL PROBLEMS 817=head1 TYPICAL PROBLEMS
794 818
795This section lists typical problems that remain. I hope by recognising 819This section lists typical problems that remain. I hope by recognising
796them, most can be avoided. 820them, most can be avoided.
797 821
798=over 4 822=over 4
799 823
800=item "leaked" file descriptors for exec'ed processes 824=item leaked file descriptors for exec'ed processes
801 825
802POSIX systems inherit file descriptors by default when exec'ing a new 826POSIX systems inherit file descriptors by default when exec'ing a new
803process. While perl itself laudably sets the close-on-exec flags on new 827process. While perl itself laudably sets the close-on-exec flags on new
804file handles, most C libraries don't care, and even if all cared, it's 828file handles, most C libraries don't care, and even if all cared, it's
805often not possible to set the flag in a race-free manner. 829often not possible to set the flag in a race-free manner.
825libraries or the code that leaks those file descriptors. 849libraries or the code that leaks those file descriptors.
826 850
827Fortunately, most of these leaked descriptors do no harm, other than 851Fortunately, most of these leaked descriptors do no harm, other than
828sitting on some resources. 852sitting on some resources.
829 853
830=item "leaked" file descriptors for fork'ed processes 854=item leaked file descriptors for fork'ed processes
831 855
832Normally, L<AnyEvent::Fork> does start new processes by exec'ing them, 856Normally, L<AnyEvent::Fork> does start new processes by exec'ing them,
833which closes file descriptors not marked for being inherited. 857which closes file descriptors not marked for being inherited.
834 858
835However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer 859However, L<AnyEvent::Fork::Early> and L<AnyEvent::Fork::Template> offer
844 868
845The solution is to either not load these modules before use'ing 869The solution is to either not load these modules before use'ing
846L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay 870L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay
847initialising them, for example, by calling C<init Gtk2> manually. 871initialising them, for example, by calling C<init Gtk2> manually.
848 872
849=item exit runs destructors 873=item exiting calls object destructors
850 874
851This only applies to users of Lc<AnyEvent::Fork:Early> and 875This only applies to users of L<AnyEvent::Fork:Early> and
852L<AnyEvent::Fork::Template>. 876L<AnyEvent::Fork::Template>, or when initialiasing code creates objects
877that reference external resources.
853 878
854When a process created by AnyEvent::Fork exits, it might do so by calling 879When a process created by AnyEvent::Fork exits, it might do so by calling
855exit, or simply letting perl reach the end of the program. At which point 880exit, or simply letting perl reach the end of the program. At which point
856Perl runs all destructors. 881Perl runs all destructors.
857 882
876to make it so, mostly due to the bloody broken perl that nobody seems to 901to make it so, mostly due to the bloody broken perl that nobody seems to
877care about. The fork emulation is a bad joke - I have yet to see something 902care about. The fork emulation is a bad joke - I have yet to see something
878useful that you can do with it without running into memory corruption 903useful that you can do with it without running into memory corruption
879issues or other braindamage. Hrrrr. 904issues or other braindamage. Hrrrr.
880 905
881Cygwin perl is not supported at the moment, as it should implement fd 906Cygwin perl is not supported at the moment due to some hilarious
882passing, but doesn't, and rolling my own is hard, as cygwin doesn't 907shortcomings of its API - see L<IO::FDPoll> for more details.
883support enough functionality to do it.
884 908
885=head1 SEE ALSO 909=head1 SEE ALSO
886 910
887L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter), 911L<AnyEvent::Fork::Early> (to avoid executing a perl interpreter),
888L<AnyEvent::Fork::Template> (to create a process by forking the main 912L<AnyEvent::Fork::Template> (to create a process by forking the main

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines