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.23 by root, Sat Apr 6 08:29:43 2013 UTC vs.
Revision 1.35 by root, Sat Apr 6 09:39:12 2013 UTC

4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::Fork; 7 use AnyEvent::Fork;
8 8
9 ################################################################## 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
18This module allows you to create new processes, without actually forking
19them from your current process (avoiding the problems of forking), but
20preserving most of the advantages of fork.
21
22It can be used to create new worker processes or new independent
23subprocesses for short- and long-running jobs, process pools (e.g. for use
24in pre-forked servers) but also to spawn new external processes (such as
25CGI scripts from a web server), which can be faster (and more well behaved)
26than using fork+exec in big processes.
27
28Special care has been taken to make this module useful from other modules,
29while still supporting specialised environments such as L<App::Staticperl>
30or L<PAR::Packer>.
31
32=head1 WHAT THIS MODULE IS NOT
33
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 -
36there is no back channel from the process back to you, and there is no RPC
37or message passing going on.
38
39If you need some form of RPC, you can either implement it yourself
40in whatever way you like, use some message-passing module such
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,
43and so on.
44
45=head1 PROBLEM STATEMENT
46
47There are two traditional ways to implement parallel processing on UNIX
48like operating systems - fork and process, and fork+exec and process. They
49have different advantages and disadvantages that I describe below,
50together with how this module tries to mitigate the disadvantages.
51
52=over 4
53
54=item Forking from a big process can be very slow.
55
56A 5GB process needs 0.05s to fork on my 3.6GHz amd64 GNU/Linux box. This
57overhead is often shared with exec (because you have to fork first), but
58in some circumstances (e.g. when vfork is used), fork+exec can be much
59faster.
60
61This module can help here by telling a small(er) helper process to fork,
62which is faster then forking the main process, and also uses vfork where
63possible. This gives the speed of vfork, with the flexibility of fork.
64
65=item Forking usually creates a copy-on-write copy of the parent
66process.
67
68For example, modules or data files that are loaded will not use additional
69memory after a fork. When exec'ing a new process, modules and data files
70might need to be loaded again, at extra CPU and memory cost. But when
71forking, literally all data structures are copied - if the program frees
72them and replaces them by new data, the child processes will retain the
73old version even if it isn't used, which can suddenly and unexpectedly
74increase memory usage when freeing memory.
75
76The trade-off is between more sharing with fork (which can be good or
77bad), and no sharing with exec.
78
79This module allows the main program to do a controlled fork, and allows
80modules to exec processes safely at any time. When creating a custom
81process pool you can take advantage of data sharing via fork without
82risking to share large dynamic data structures that will blow up child
83memory usage.
84
85In other words, this module puts you into control over what is being
86shared and what isn't, at all times.
87
88=item Exec'ing a new perl process might be difficult.
89
90For example, it is not easy to find the correct path to the perl
91interpreter - C<$^X> might not be a perl interpreter at all.
92
93This module tries hard to identify the correct path to the perl
94interpreter. With a cooperative main program, exec'ing the interpreter
95might not even be necessary, but even without help from the main program,
96it will still work when used from a module.
97
98=item Exec'ing a new perl process might be slow, as all necessary modules
99have to be loaded from disk again, with no guarantees of success.
100
101Long running processes might run into problems when perl is upgraded
102and modules are no longer loadable because they refer to a different
103perl version, or parts of a distribution are newer than the ones already
104loaded.
105
106This module supports creating pre-initialised perl processes to be used as
107a template for new processes.
108
109=item Forking might be impossible when a program is running.
110
111For example, POSIX makes it almost impossible to fork from a
112multi-threaded program while doing anything useful in the child - in
113fact, if your perl program uses POSIX threads (even indirectly via
114e.g. L<IO::AIO> or L<threads>), you cannot call fork on the perl level
115anymore without risking corruption issues on a number of operating
116systems.
117
118This module can safely fork helper processes at any time, by calling
119fork+exec in C, in a POSIX-compatible way (via L<Proc::FastSpawn>).
120
121=item Parallel processing with fork might be inconvenient or difficult
122to implement. Modules might not work in both parent and child.
123
124For example, when a program uses an event loop and creates watchers it
125becomes very hard to use the event loop from a child program, as the
126watchers already exist but are only meaningful in the parent. Worse, a
127module might want to use such a module, not knowing whether another module
128or the main program also does, leading to problems.
129
130Apart from event loops, graphical toolkits also commonly fall into the
131"unsafe module" category, or just about anything that communicates with
132the external world, such as network libraries and file I/O modules, which
133usually don't like being copied and then allowed to continue in two
134processes.
135
136With this module only the main program is allowed to create new processes
137by forking (because only the main program can know when it is still safe
138to do so) - all other processes are created via fork+exec, which makes it
139possible to use modules such as event loops or window interfaces safely.
140
141=back
142
143=head1 EXAMPLES
144
10 # create a single new process, tell it to run your worker function 145=head2 Create a single new process, tell it to run your worker function.
11 146
12 AnyEvent::Fork 147 AnyEvent::Fork
13 ->new 148 ->new
14 ->require ("MyModule") 149 ->require ("MyModule")
15 ->run ("MyModule::worker, sub { 150 ->run ("MyModule::worker, sub {
17 152
18 # now $master_filehandle is connected to the 153 # now $master_filehandle is connected to the
19 # $slave_filehandle in the new process. 154 # $slave_filehandle in the new process.
20 }); 155 });
21 156
22 # MyModule::worker might look like this 157C<MyModule> might look like this:
158
159 package MyModule;
160
23 sub MyModule::worker { 161 sub worker {
24 my ($slave_filehandle) = @_; 162 my ($slave_filehandle) = @_;
25 163
26 # now $slave_filehandle is connected to the $master_filehandle 164 # now $slave_filehandle is connected to the $master_filehandle
27 # in the original prorcess. have fun! 165 # in the original prorcess. have fun!
28 } 166 }
29 167
30 ##################################################################
31 # create a pool of server processes all accepting on the same socket 168=head2 Create a pool of server processes all accepting on the same socket.
32 169
33 # create listener socket 170 # create listener socket
34 my $listener = ...; 171 my $listener = ...;
35 172
36 # create a pool template, initialise it and give it the socket 173 # create a pool template, initialise it and give it the socket
48 } 185 }
49 186
50 # now do other things - maybe use the filehandle provided by run 187 # now do other things - maybe use the filehandle provided by run
51 # to wait for the processes to die. or whatever. 188 # to wait for the processes to die. or whatever.
52 189
53 # My::Server::run might look like this 190C<My::Server> might look like this:
54 sub My::Server::run { 191
192 package My::Server;
193
194 sub run {
55 my ($slave, $listener, $id) = @_; 195 my ($slave, $listener, $id) = @_;
56 196
57 close $slave; # we do not use the socket, so close it to save resources 197 close $slave; # we do not use the socket, so close it to save resources
58 198
59 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO, 199 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
61 while (my $socket = $listener->accept) { 201 while (my $socket = $listener->accept) {
62 # do sth. with new socket 202 # do sth. with new socket
63 } 203 }
64 } 204 }
65 205
66 ##################################################################
67 # use AnyEvent::Fork as a faster fork+exec 206=head2 use AnyEvent::Fork as a faster fork+exec
68 207
69 # this runs /bin/echo hi, with stdout redirected to /tmp/log 208This runs C</bin/echo hi>, with stdandard output redirected to /tmp/log
70 # and stderr to the communications socket. it is usually faster 209and standard error redirected to the communications socket. It is usually
71 # than fork+exec, but still let's you prepare the environment. 210faster than fork+exec, but still lets you prepare the environment.
72 211
73 open my $output, ">/tmp/log" or die "$!"; 212 open my $output, ">/tmp/log" or die "$!";
74 213
75 AnyEvent::Fork 214 AnyEvent::Fork
76 ->new 215 ->new
88 ->send_fh ($output) 227 ->send_fh ($output)
89 ->send_arg ("/bin/echo", "hi") 228 ->send_arg ("/bin/echo", "hi")
90 ->run ("run", my $cv = AE::cv); 229 ->run ("run", my $cv = AE::cv);
91 230
92 my $stderr = $cv->recv; 231 my $stderr = $cv->recv;
93
94=head1 DESCRIPTION
95
96This module allows you to create new processes, without actually forking
97them from your current process (avoiding the problems of forking), but
98preserving most of the advantages of fork.
99
100It can be used to create new worker processes or new independent
101subprocesses for short- and long-running jobs, process pools (e.g. for use
102in pre-forked servers) but also to spawn new external processes (such as
103CGI scripts from a web server), which can be faster (and more well behaved)
104than using fork+exec in big processes.
105
106Special care has been taken to make this module useful from other modules,
107while still supporting specialised environments such as L<App::Staticperl>
108or L<PAR::Packer>.
109
110=head1 WHAT THIS MODULE IS NOT
111
112This module only creates processes and lets you pass file handles and
113strings to it, and run perl code. It does not implement any kind of RPC -
114there is no back channel from the process back to you, and there is no RPC
115or message passing going on.
116
117If you need some form of RPC, you can either implement it yourself
118in whatever way you like, use some message-passing module such
119as L<AnyEvent::MP>, some pipe such as L<AnyEvent::ZeroMQ>, use
120L<AnyEvent::Handle> on both sides to send e.g. JSON or Storable messages,
121and so on.
122
123=head1 PROBLEM STATEMENT
124
125There are two ways to implement parallel processing on UNIX like operating
126systems - fork and process, and fork+exec and process. They have different
127advantages and disadvantages that I describe below, together with how this
128module tries to mitigate the disadvantages.
129
130=over 4
131
132=item Forking from a big process can be very slow (a 5GB process needs
1330.05s to fork on my 3.6GHz amd64 GNU/Linux box for example). This overhead
134is often shared with exec (because you have to fork first), but in some
135circumstances (e.g. when vfork is used), fork+exec can be much faster.
136
137This module can help here by telling a small(er) helper process to fork,
138or fork+exec instead.
139
140=item Forking usually creates a copy-on-write copy of the parent
141process. Memory (for example, modules or data files that have been
142will not take additional memory). When exec'ing a new process, modules
143and data files might need to be loaded again, at extra CPU and memory
144cost. Likewise when forking, all data structures are copied as well - if
145the program frees them and replaces them by new data, the child processes
146will retain the memory even if it isn't used.
147
148This module allows the main program to do a controlled fork, and allows
149modules to exec processes safely at any time. When creating a custom
150process pool you can take advantage of data sharing via fork without
151risking to share large dynamic data structures that will blow up child
152memory usage.
153
154=item Exec'ing a new perl process might be difficult and slow. For
155example, it is not easy to find the correct path to the perl interpreter,
156and all modules have to be loaded from disk again. Long running processes
157might run into problems when perl is upgraded for example.
158
159This module supports creating pre-initialised perl processes to be used
160as template, and also tries hard to identify the correct path to the perl
161interpreter. With a cooperative main program, exec'ing the interpreter
162might not even be necessary.
163
164=item Forking might be impossible when a program is running. For example,
165POSIX makes it almost impossible to fork from a multi-threaded program and
166do anything useful in the child - strictly speaking, if your perl program
167uses posix threads (even indirectly via e.g. L<IO::AIO> or L<threads>),
168you cannot call fork on the perl level anymore, at all.
169
170This module can safely fork helper processes at any time, by calling
171fork+exec in C, in a POSIX-compatible way.
172
173=item Parallel processing with fork might be inconvenient or difficult
174to implement. For example, when a program uses an event loop and creates
175watchers it becomes very hard to use the event loop from a child
176program, as the watchers already exist but are only meaningful in the
177parent. Worse, a module might want to use such a system, not knowing
178whether another module or the main program also does, leading to problems.
179
180This module only lets the main program create pools by forking (because
181only the main program can know when it is still safe to do so) - all other
182pools are created by fork+exec, after which such modules can again be
183loaded.
184
185=back
186 232
187=head1 CONCEPTS 233=head1 CONCEPTS
188 234
189This module can create new processes either by executing a new perl 235This module can create new processes either by executing a new perl
190process, or by forking from an existing "template" process. 236process, or by forking from an existing "template" process.
269 my ($fork_fh) = @_; 315 my ($fork_fh) = @_;
270 }); 316 });
271 317
272=back 318=back
273 319
274=head1 FUNCTIONS 320=head1 THE C<AnyEvent::Fork> CLASS
321
322This module exports nothing, and only implements a single class -
323C<AnyEvent::Fork>.
324
325There are two class constructors that both create new processes - C<new>
326and C<new_exec>. The C<fork> method creates a new process by forking an
327existing one and could be considered a third constructor.
328
329Most of the remaining methods deal with preparing the new process, by
330loading code, evaluating code and sending data to the new process. They
331usually return the process object, so you can chain method calls.
332
333If a process object is destroyed before calling its C<run> method, then
334the process simply exits. After C<run> is called, all responsibility is
335passed to the specified function.
336
337As long as there is any outstanding work to be done, process objects
338resist being destroyed, so there is no reason to store them unless you
339need them later - configure and forget works just fine.
275 340
276=over 4 341=over 4
277 342
278=cut 343=cut
279 344
289use IO::FDPass; 354use IO::FDPass;
290 355
291our $VERSION = 0.5; 356our $VERSION = 0.5;
292 357
293our $PERL; # the path to the perl interpreter, deduces with various forms of magic 358our $PERL; # the path to the perl interpreter, deduces with various forms of magic
294
295=item my $pool = new AnyEvent::Fork key => value...
296
297Create a new process pool. The following named parameters are supported:
298 359
299=over 4 360=over 4
300 361
301=back 362=back
302 363
398Create a new "empty" perl interpreter process and returns its process 459Create a new "empty" perl interpreter process and returns its process
399object for further manipulation. 460object for further manipulation.
400 461
401The new process is forked from a template process that is kept around 462The new process is forked from a template process that is kept around
402for this purpose. When it doesn't exist yet, it is created by a call to 463for this purpose. When it doesn't exist yet, it is created by a call to
403C<new_exec> and kept around for future calls. 464C<new_exec> first and then stays around for future calls.
404
405When the process object is destroyed, it will release the file handle
406that connects it with the new process. When the new process has not yet
407called C<run>, then the process will exit. Otherwise, what happens depends
408entirely on the code that is executed.
409 465
410=cut 466=cut
411 467
412sub new { 468sub new {
413 my $class = shift; 469 my $class = shift;
503} 559}
504 560
505=item $pid = $proc->pid 561=item $pid = $proc->pid
506 562
507Returns the process id of the process I<iff it is a direct child of the 563Returns the process id of the process I<iff it is a direct child of the
508process> running AnyEvent::Fork, and C<undef> otherwise. 564process running AnyEvent::Fork>, and C<undef> otherwise.
509 565
510Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and 566Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and
511L<AnyEvent::Fork::Template> are direct children, and you are responsible 567L<AnyEvent::Fork::Template> are direct children, and you are responsible
512to clean up their zombies when they die. 568to clean up their zombies when they die.
513 569
514All other processes are not direct children, and will be cleaned up by 570All other processes are not direct children, and will be cleaned up by
515AnyEvent::Fork. 571AnyEvent::Fork itself.
516 572
517=cut 573=cut
518 574
519sub pid { 575sub pid {
520 $_[0][0] 576 $_[0][0]
531 587
532The code will usually be executed after this call returns, and there is no 588The code will usually be executed after this call returns, and there is no
533way to pass anything back to the calling process. Any evaluation errors 589way to pass anything back to the calling process. Any evaluation errors
534will be reported to stderr and cause the process to exit. 590will be reported to stderr and cause the process to exit.
535 591
536If you want to execute some code to take over the process (see the 592If you want to execute some code (that isn't in a module) to take over the
537"fork+exec" example in the SYNOPSIS), you should compile a function via 593process, you should compile a function via C<eval> first, and then call
538C<eval> first, and then call it via C<run>. This also gives you access to 594it via C<run>. This also gives you access to any arguments passed via the
539any arguments passed via the C<send_xxx> methods, such as file handles. 595C<send_xxx> methods, such as file handles. See the L<use AnyEvent::Fork as
596a faster fork+exec> example to see it in action.
540 597
541Returns the process object for easy chaining of method calls. 598Returns the process object for easy chaining of method calls.
542 599
543=cut 600=cut
544 601
570=item $proc = $proc->send_fh ($handle, ...) 627=item $proc = $proc->send_fh ($handle, ...)
571 628
572Send one or more file handles (I<not> file descriptors) to the process, 629Send one or more file handles (I<not> file descriptors) to the process,
573to prepare a call to C<run>. 630to prepare a call to C<run>.
574 631
575The process object keeps a reference to the handles until this is done, 632The process object keeps a reference to the handles until they have
576so you must not explicitly close the handles. This is most easily 633been passed over to the process, so you must not explicitly close the
577accomplished by simply not storing the file handles anywhere after passing 634handles. This is most easily accomplished by simply not storing the file
578them to this method. 635handles anywhere after passing them to this method - when AnyEvent::Fork
636is finished using them, perl will automatically close them.
579 637
580Returns the process object for easy chaining of method calls. 638Returns the process object for easy chaining of method calls.
581 639
582Example: pass a file handle to a process, and release it without 640Example: pass a file handle to a process, and release it without
583closing. It will be closed automatically when it is no longer used. 641closing. It will be closed automatically when it is no longer used.
599} 657}
600 658
601=item $proc = $proc->send_arg ($string, ...) 659=item $proc = $proc->send_arg ($string, ...)
602 660
603Send one or more argument strings to the process, to prepare a call to 661Send one or more argument strings to the process, to prepare a call to
604C<run>. The strings can be any octet string. 662C<run>. The strings can be any octet strings.
605 663
606The protocol is optimised to pass a moderate number of relatively short 664The protocol is optimised to pass a moderate number of relatively short
607strings - while you can pass up to 4GB of data in one go, this is more 665strings - while you can pass up to 4GB of data in one go, this is more
608meant to pass some ID information or other startup info, not big chunks of 666meant to pass some ID information or other startup info, not big chunks of
609data. 667data.
625Enter the function specified by the function name in C<$func> in the 683Enter the function specified by the function name in C<$func> in the
626process. The function is called with the communication socket as first 684process. The function is called with the communication socket as first
627argument, followed by all file handles and string arguments sent earlier 685argument, followed by all file handles and string arguments sent earlier
628via C<send_fh> and C<send_arg> methods, in the order they were called. 686via C<send_fh> and C<send_arg> methods, in the order they were called.
629 687
688The process object becomes unusable on return from this function - any
689further method calls result in undefined behaviour.
690
630The function name should be fully qualified, but if it isn't, it will be 691The function name should be fully qualified, but if it isn't, it will be
631looked up in the main package. 692looked up in the C<main> package.
632 693
633If the called function returns, doesn't exist, or any error occurs, the 694If the called function returns, doesn't exist, or any error occurs, the
634process exits. 695process exits.
635 696
636Preparing the process is done in the background - when all commands have 697Preparing the process is done in the background - when all commands have
637been sent, the callback is invoked with the local communications socket 698been sent, the callback is invoked with the local communications socket
638as argument. At this point you can start using the socket in any way you 699as argument. At this point you can start using the socket in any way you
639like. 700like.
640
641The process object becomes unusable on return from this function - any
642further method calls result in undefined behaviour.
643 701
644If the communication socket isn't used, it should be closed on both sides, 702If the communication socket isn't used, it should be closed on both sides,
645to save on kernel memory. 703to save on kernel memory.
646 704
647The socket is non-blocking in the parent, and blocking in the newly 705The socket is non-blocking in the parent, and blocking in the newly

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines