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.8 by root, Thu Apr 4 01:54:40 2013 UTC vs.
Revision 1.9 by root, Thu Apr 4 03:45:12 2013 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::Fork - everything you wanted to use fork() for, but couldn't 3AnyEvent::Fork - everything you wanted to use fork() for, but couldn't
4 4
5ATTENTION, this is a very early release, and very untested. Consider it a
6technology preview.
7
5=head1 SYNOPSIS 8=head1 SYNOPSIS
6 9
7 use AnyEvent::Fork; 10 use AnyEvent::Fork;
11
12 ##################################################################
13 # create a single new process, tell it to run your worker function
14
15 AnyEvent::Fork
16 ->new
17 ->require ("MyModule")
18 ->run ("MyModule::worker, sub {
19 my ($master_filehandle) = @_;
20
21 # now $master_filehandle is connected to the
22 # $slave_filehandle in the new process.
23 });
24
25 # MyModule::worker might look like this
26 sub MyModule::worker {
27 my ($slave_filehandle) = @_;
28
29 # now $slave_filehandle is connected to the $master_filehandle
30 # in the original prorcess. have fun!
31 }
32
33 ##################################################################
34 # create a pool of server processes all accepting on the same socket
35
36 # create listener socket
37 my $listener = ...;
38
39 # create a pool template, initialise it and give it the socket
40 my $pool = AnyEvent::Fork
41 ->new
42 ->require ("Some::Stuff", "My::Server")
43 ->send_fh ($listener);
44
45 # now create 10 identical workers
46 for my $id (1..10) {
47 $pool
48 ->fork
49 ->send_arg ($id)
50 ->run ("My::Server::run");
51 }
52
53 # now do other things - maybe use the filehandle provided by run
54 # to wait for the processes to die. or whatever.
55
56 # My::Server::run might look like this
57 sub My::Server::run {
58 my ($slave, $listener, $id) = @_;
59
60 close $slave; # we do not use the socket, so close it to save resources
61
62 # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
63 # or anything we usually couldn't do in a process forked normally.
64 while (my $socket = $listener->accept) {
65 # do sth. with new socket
66 }
67 }
8 68
9=head1 DESCRIPTION 69=head1 DESCRIPTION
10 70
11This module allows you to create new processes, without actually forking 71This module allows you to create new processes, without actually forking
12them from your current process (avoiding the problems of forking), but 72them from your current process (avoiding the problems of forking), but
111time, and the memory is not shared with anything else. 171time, and the memory is not shared with anything else.
112 172
113This is ideal for when you only need one extra process of a kind, with the 173This is ideal for when you only need one extra process of a kind, with the
114option of starting and stipping it on demand. 174option of starting and stipping it on demand.
115 175
176Example:
177
178 AnyEvent::Fork
179 ->new
180 ->require ("Some::Module")
181 ->run ("Some::Module::run", sub {
182 my ($fork_fh) = @_;
183 });
184
116=item fork a new template process, load code, then fork processes off of 185=item fork a new template process, load code, then fork processes off of
117it and run the code 186it and run the code
118 187
119When you need to have a bunch of processes that all execute the same (or 188When you need to have a bunch of processes that all execute the same (or
120very similar) tasks, then a good way is to create a new template process 189very similar) tasks, then a good way is to create a new template process
128The disadvantage of this approach is that you need to create a template 197The disadvantage of this approach is that you need to create a template
129process for the sole purpose of forking new processes from it, but if you 198process for the sole purpose of forking new processes from it, but if you
130only need a fixed number of proceses you can create them, and then destroy 199only need a fixed number of proceses you can create them, and then destroy
131the template process. 200the template process.
132 201
202Example:
203
204 my $template = AnyEvent::Fork->new->require ("Some::Module");
205
206 for (1..10) {
207 $template->fork->run ("Some::Module::run", sub {
208 my ($fork_fh) = @_;
209 });
210 }
211
212 # at this point, you can keep $template around to fork new processes
213 # later, or you can destroy it, which causes it to vanish.
214
133=item execute a new perl interpreter, load some code, run it 215=item execute a new perl interpreter, load some code, run it
134 216
135This is relatively slow, and doesn't allow you to share memory between 217This is relatively slow, and doesn't allow you to share memory between
136multiple processes. 218multiple processes.
137 219
138The only advantage is that you don't have to have a template process 220The only advantage is that you don't have to have a template process
139hanging around all the time to fork off some new processes, which might be 221hanging around all the time to fork off some new processes, which might be
140an advantage when there are long time spans where no extra processes are 222an advantage when there are long time spans where no extra processes are
141needed. 223needed.
142 224
225Example:
226
227 AnyEvent::Fork
228 ->new_exec
229 ->require ("Some::Module")
230 ->run ("Some::Module::run", sub {
231 my ($fork_fh) = @_;
232 });
233
143=back 234=back
144 235
145=head1 FUNCTIONS 236=head1 FUNCTIONS
146 237
147=over 4 238=over 4
177our $TEMPLATE; 268our $TEMPLATE;
178 269
179sub _cmd { 270sub _cmd {
180 my $self = shift; 271 my $self = shift;
181 272
273 #TODO: maybe append the packet to any existing string command already in the queue
274
182 # ideally, we would want to use "a (w/a)*" as format string, but perl versions 275 # ideally, we would want to use "a (w/a)*" as format string, but perl versions
183 # from at least 5.8.9 to 5.16.3 are all buggy and can't unpack it. 276 # from at least 5.8.9 to 5.16.3 are all buggy and can't unpack it.
184 push @{ $self->[2] }, pack "N/a", pack "(w/a)*", @_; 277 push @{ $self->[2] }, pack "N/a", pack "(w/a)*", @_;
185 278
186 $self->[3] ||= AE::io $self->[1], 1, sub { 279 $self->[3] ||= AE::io $self->[1], 1, sub {
280 # send the next "thing" in the queue - either a reference to an fh,
281 # or a plain string.
282
187 if (ref $self->[2][0]) { 283 if (ref $self->[2][0]) {
284 # send fh
188 AnyEvent::Fork::Util::fd_send fileno $self->[1], fileno ${ $self->[2][0] } 285 AnyEvent::Fork::Util::fd_send fileno $self->[1], fileno ${ $self->[2][0] }
189 and shift @{ $self->[2] }; 286 and shift @{ $self->[2] };
190 287
191 } else { 288 } else {
289 # send string
192 my $len = syswrite $self->[1], $self->[2][0] 290 my $len = syswrite $self->[1], $self->[2][0]
193 or do { undef $self->[3]; die "AnyEvent::Fork: command write failure: $!" }; 291 or do { undef $self->[3]; die "AnyEvent::Fork: command write failure: $!" };
194 292
195 substr $self->[2][0], 0, $len, ""; 293 substr $self->[2][0], 0, $len, "";
196 shift @{ $self->[2] } unless length $self->[2][0]; 294 shift @{ $self->[2] } unless length $self->[2][0];
197 } 295 }
198 296
199 unless (@{ $self->[2] }) { 297 unless (@{ $self->[2] }) {
200 undef $self->[3]; 298 undef $self->[3];
299 # invoke run callback
201 $self->[0]->($self->[1]) if $self->[0]; 300 $self->[0]->($self->[1]) if $self->[0];
202 } 301 }
203 }; 302 };
204} 303}
205 304
212 undef, # run callback 311 undef, # run callback
213 $fh, 312 $fh,
214 [], # write queue - strings or fd's 313 [], # write queue - strings or fd's
215 undef, # AE watcher 314 undef, # AE watcher
216 ], $self; 315 ], $self;
217
218# my ($a, $b) = AnyEvent::Util::portable_socketpair;
219
220# queue_cmd $template, "Iabc";
221# push @{ $template->[2] }, \$b;
222
223# use Coro::AnyEvent; Coro::AnyEvent::sleep 1;
224# undef $b;
225# die "x" . <$a>;
226 316
227 $self 317 $self
228} 318}
229 319
230# fork template from current process, used by AnyEvent::Fork::Early/Template 320# fork template from current process, used by AnyEvent::Fork::Early/Template
254object for further manipulation. 344object for further manipulation.
255 345
256The new process is forked from a template process that is kept around 346The new process is forked from a template process that is kept around
257for this purpose. When it doesn't exist yet, it is created by a call to 347for this purpose. When it doesn't exist yet, it is created by a call to
258C<new_exec> and kept around for future calls. 348C<new_exec> and kept around for future calls.
349
350When the process object is destroyed, it will release the file handle
351that connects it with the new process. When the new process has not yet
352called C<run>, then the process will exit. Otherwise, what happens depends
353entirely on the code that is executed.
259 354
260=cut 355=cut
261 356
262sub new { 357sub new {
263 my $class = shift; 358 my $class = shift;
346 ) or die "unable to spawn AnyEvent::Fork server: $!"; 441 ) or die "unable to spawn AnyEvent::Fork server: $!";
347 442
348 $self->_new ($fh) 443 $self->_new ($fh)
349} 444}
350 445
446=item $proc = $proc->eval ($perlcode, @args)
447
448Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to
449the strings specified by C<@args>.
450
451This call is meant to do any custom initialisation that might be required
452(for example, the C<require> method uses it). It's not supposed to be used
453to completely take over the process, use C<run> for that.
454
455The code will usually be executed after this call returns, and there is no
456way to pass anything back to the calling process. Any evaluation errors
457will be reported to stderr and cause the process to exit.
458
459Returns the process object for easy chaining of method calls.
460
461=cut
462
463sub eval {
464 my ($self, $code, @args) = @_;
465
466 $self->_cmd (e => $code, @args);
467
468 $self
469}
470
351=item $proc = $proc->require ($module, ...) 471=item $proc = $proc->require ($module, ...)
352 472
353Tries to load the given modules into the process 473Tries to load the given module(s) into the process
354 474
355Returns the process object for easy chaining of method calls. 475Returns the process object for easy chaining of method calls.
476
477=cut
478
479sub require {
480 my ($self, @modules) = @_;
481
482 s%::%/%g for @modules;
483 $self->eval ('require "$_.pm" for @_', @modules);
484
485 $self
486}
356 487
357=item $proc = $proc->send_fh ($handle, ...) 488=item $proc = $proc->send_fh ($handle, ...)
358 489
359Send one or more file handles (I<not> file descriptors) to the process, 490Send one or more file handles (I<not> file descriptors) to the process,
360to prepare a call to C<run>. 491to prepare a call to C<run>.
364accomplished by simply not storing the file handles anywhere after passing 495accomplished by simply not storing the file handles anywhere after passing
365them to this method. 496them to this method.
366 497
367Returns the process object for easy chaining of method calls. 498Returns the process object for easy chaining of method calls.
368 499
500Example: pass an fh to a process, and release it without closing. it will
501be closed automatically when it is no longer used.
502
503 $proc->send_fh ($my_fh);
504 undef $my_fh; # free the reference if you want, but DO NOT CLOSE IT
505
369=cut 506=cut
370 507
371sub send_fh { 508sub send_fh {
372 my ($self, @fh) = @_; 509 my ($self, @fh) = @_;
373 510
374 for my $fh (@fh) { 511 for my $fh (@fh) {
375 $self->_cmd ("h"); 512 $self->_cmd ("h");
376 push @{ $self->[2] }, \$fh; 513 push @{ $self->[2] }, \$fh;
377 push @$self, $fh; # dire hack
378 } 514 }
379 515
380 $self 516 $self
381} 517}
382 518
419otherwise, the socket can be a good indicator for the existance of the 555otherwise, the socket can be a good indicator for the existance of the
420process - if the other process exits, you get a readable event on it, 556process - if the other process exits, you get a readable event on it,
421because exiting the process closes the socket (if it didn't create any 557because exiting the process closes the socket (if it didn't create any
422children using fork). 558children using fork).
423 559
560Example: create a template for a process pool, pass a few strings, some
561file handles, then fork, pass one more string, and run some code.
562
563 my $pool = AnyEvent::Fork
564 ->new
565 ->send_arg ("str1", "str2")
566 ->send_fh ($fh1, $fh2);
567
568 for (1..2) {
569 $pool
570 ->fork
571 ->send_arg ("str3")
572 ->run ("Some::function", sub {
573 my ($fh) = @_;
574
575 # fh is nonblocking, but we trust that the OS can accept these
576 # extra 3 octets anyway.
577 syswrite $fh, "hi #$_\n";
578
579 # $fh is being closed here, as we don't store it anywhere
580 });
581 }
582
583 # Some::function might look like this - all parameters passed before fork
584 # and after will be passed, in order, after the communications socket.
585 sub Some::function {
586 my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_;
587
588 print scalar <$fh>; # prints "hi 1\n" and "hi 2\n"
589 }
590
424=cut 591=cut
425 592
426sub run { 593sub run {
427 my ($self, $func, $cb) = @_; 594 my ($self, $func, $cb) = @_;
428 595
429 $self->[0] = $cb; 596 $self->[0] = $cb;
430 $self->_cmd ("r", $func); 597 $self->_cmd (r => $func);
431} 598}
432 599
433=back 600=back
434 601
435=head1 PORTABILITY NOTES 602=head1 PORTABILITY NOTES

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines