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.18 by root, Sat Apr 6 01:33:56 2013 UTC vs.
Revision 1.23 by root, Sat Apr 6 08:29:43 2013 UTC

61 while (my $socket = $listener->accept) { 61 while (my $socket = $listener->accept) {
62 # do sth. with new socket 62 # do sth. with new socket
63 } 63 }
64 } 64 }
65 65
66 ##################################################################
67 # use AnyEvent::Fork as a faster fork+exec
68
69 # this runs /bin/echo hi, with stdout redirected to /tmp/log
70 # and stderr to the communications socket. it is usually faster
71 # than fork+exec, but still let's you prepare the environment.
72
73 open my $output, ">/tmp/log" or die "$!";
74
75 AnyEvent::Fork
76 ->new
77 ->eval ('
78 sub run {
79 my ($fh, $output, @cmd) = @_;
80
81 # perl will clear close-on-exec on STDOUT/STDERR
82 open STDOUT, ">&", $output or die;
83 open STDERR, ">&", $fh or die;
84
85 exec @cmd;
86 }
87 ')
88 ->send_fh ($output)
89 ->send_arg ("/bin/echo", "hi")
90 ->run ("run", my $cv = AE::cv);
91
92 my $stderr = $cv->recv;
93
66=head1 DESCRIPTION 94=head1 DESCRIPTION
67 95
68This module allows you to create new processes, without actually forking 96This module allows you to create new processes, without actually forking
69them from your current process (avoiding the problems of forking), but 97them from your current process (avoiding the problems of forking), but
70preserving most of the advantages of fork. 98preserving most of the advantages of fork.
258use AnyEvent; 286use AnyEvent;
259use AnyEvent::Util (); 287use AnyEvent::Util ();
260 288
261use IO::FDPass; 289use IO::FDPass;
262 290
263our $VERSION = 0.2; 291our $VERSION = 0.5;
264 292
265our $PERL; # the path to the perl interpreter, deduces with various forms of magic 293our $PERL; # the path to the perl interpreter, deduces with various forms of magic
266 294
267=item my $pool = new AnyEvent::Fork key => value... 295=item my $pool = new AnyEvent::Fork key => value...
268 296
284 my $self = shift; 312 my $self = shift;
285 313
286 # ideally, we would want to use "a (w/a)*" as format string, but perl 314 # ideally, we would want to use "a (w/a)*" as format string, but perl
287 # versions from at least 5.8.9 to 5.16.3 are all buggy and can't unpack 315 # versions from at least 5.8.9 to 5.16.3 are all buggy and can't unpack
288 # it. 316 # it.
289 push @{ $self->[2] }, pack "L/a*", pack "(w/a*)*", @_; 317 push @{ $self->[2] }, pack "a L/a*", $_[0], $_[1];
290 318
291 unless ($self->[3]) { 319 $self->[3] ||= AE::io $self->[1], 1, sub {
292 my $wcb = sub {
293 do { 320 do {
294 # send the next "thing" in the queue - either a reference to an fh, 321 # send the next "thing" in the queue - either a reference to an fh,
295 # or a plain string. 322 # or a plain string.
296 323
297 if (ref $self->[2][0]) { 324 if (ref $self->[2][0]) {
298 # send fh 325 # send fh
299 unless (IO::FDPass::send fileno $self->[1], fileno ${ $self->[2][0] }) { 326 unless (IO::FDPass::send fileno $self->[1], fileno ${ $self->[2][0] }) {
300 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK; 327 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK;
301 undef $self->[3]; 328 undef $self->[3];
302 die "AnyEvent::Fork: file descriptor send failure: $!"; 329 die "AnyEvent::Fork: file descriptor send failure: $!";
303 }
304
305 shift @{ $self->[2] };
306
307 } else {
308 # send string
309 my $len = syswrite $self->[1], $self->[2][0];
310
311 unless ($len) {
312 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK;
313 undef $self->[3];
314 die "AnyEvent::Fork: command write failure: $!";
315 }
316
317 substr $self->[2][0], 0, $len, "";
318 shift @{ $self->[2] } unless length $self->[2][0];
319 } 330 }
331
332 shift @{ $self->[2] };
333
334 } else {
335 # send string
336 my $len = syswrite $self->[1], $self->[2][0];
337
338 unless ($len) {
339 return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK;
340 undef $self->[3];
341 die "AnyEvent::Fork: command write failure: $!";
342 }
343
344 substr $self->[2][0], 0, $len, "";
345 shift @{ $self->[2] } unless length $self->[2][0];
346 }
320 } while @{ $self->[2] }; 347 } while @{ $self->[2] };
321 348
322 # everything written 349 # everything written
323 undef $self->[3]; 350 undef $self->[3];
351
324 # invoke run callback 352 # invoke run callback, if any
325 $self->[0]->($self->[1]) if $self->[0]; 353 $self->[4]->($self->[1]) if $self->[4];
326 };
327
328 $wcb->();
329
330 $self->[3] ||= AE::io $self->[1], 1, $wcb
331 if @{ $self->[2] };
332 } 354 };
333 355
334 () # make sure we don't leak the watcher 356 () # make sure we don't leak the watcher
335} 357}
336 358
337sub _new { 359sub _new {
338 my ($self, $fh) = @_; 360 my ($self, $fh, $pid) = @_;
339 361
340 AnyEvent::Util::fh_nonblocking $fh, 1; 362 AnyEvent::Util::fh_nonblocking $fh, 1;
341 363
342 $self = bless [ 364 $self = bless [
343 undef, # run callback 365 $pid,
344 $fh, 366 $fh,
345 [], # write queue - strings or fd's 367 [], # write queue - strings or fd's
346 undef, # AE watcher 368 undef, # AE watcher
347 ], $self; 369 ], $self;
348 370
366 exit 0; 388 exit 0;
367 } elsif (!$pid) { 389 } elsif (!$pid) {
368 die "AnyEvent::Fork::Early/Template: unable to fork template process: $!"; 390 die "AnyEvent::Fork::Early/Template: unable to fork template process: $!";
369 } 391 }
370 392
371 AnyEvent::Fork->_new ($fh) 393 AnyEvent::Fork->_new ($fh, $pid)
372} 394}
373 395
374=item my $proc = new AnyEvent::Fork 396=item my $proc = new AnyEvent::Fork
375 397
376Create a new "empty" perl interpreter process and returns its process 398Create a new "empty" perl interpreter process and returns its process
469 # quick. also doesn't work in win32. of course. what did you expect 491 # quick. also doesn't work in win32. of course. what did you expect
470 #local $ENV{PERL5LIB} = join ":", grep !ref, @INC; 492 #local $ENV{PERL5LIB} = join ":", grep !ref, @INC;
471 my %env = %ENV; 493 my %env = %ENV;
472 $env{PERL5LIB} = join +($^O eq "MSWin32" ? ";" : ":"), grep !ref, @INC; 494 $env{PERL5LIB} = join +($^O eq "MSWin32" ? ";" : ":"), grep !ref, @INC;
473 495
474 Proc::FastSpawn::spawn ( 496 my $pid = Proc::FastSpawn::spawn (
475 $perl, 497 $perl,
476 ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$], 498 ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$],
477 [map "$_=$env{$_}", keys %env], 499 [map "$_=$env{$_}", keys %env],
478 ) or die "unable to spawn AnyEvent::Fork server: $!"; 500 ) or die "unable to spawn AnyEvent::Fork server: $!";
479 501
480 $self->_new ($fh) 502 $self->_new ($fh, $pid)
503}
504
505=item $pid = $proc->pid
506
507Returns the process id of the process I<iff it is a direct child of the
508process> running AnyEvent::Fork, and C<undef> otherwise.
509
510Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and
511L<AnyEvent::Fork::Template> are direct children, and you are responsible
512to clean up their zombies when they die.
513
514All other processes are not direct children, and will be cleaned up by
515AnyEvent::Fork.
516
517=cut
518
519sub pid {
520 $_[0][0]
481} 521}
482 522
483=item $proc = $proc->eval ($perlcode, @args) 523=item $proc = $proc->eval ($perlcode, @args)
484 524
485Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to 525Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to
486the strings specified by C<@args>. 526the strings specified by C<@args>, in the "main" package.
487 527
488This call is meant to do any custom initialisation that might be required 528This call is meant to do any custom initialisation that might be required
489(for example, the C<require> method uses it). It's not supposed to be used 529(for example, the C<require> method uses it). It's not supposed to be used
490to completely take over the process, use C<run> for that. 530to completely take over the process, use C<run> for that.
491 531
492The code will usually be executed after this call returns, and there is no 532The code will usually be executed after this call returns, and there is no
493way to pass anything back to the calling process. Any evaluation errors 533way to pass anything back to the calling process. Any evaluation errors
494will be reported to stderr and cause the process to exit. 534will be reported to stderr and cause the process to exit.
495 535
536If you want to execute some code to take over the process (see the
537"fork+exec" example in the SYNOPSIS), you should compile a function via
538C<eval> first, and then call it via C<run>. This also gives you access to
539any arguments passed via the C<send_xxx> methods, such as file handles.
540
496Returns the process object for easy chaining of method calls. 541Returns the process object for easy chaining of method calls.
497 542
498=cut 543=cut
499 544
500sub eval { 545sub eval {
501 my ($self, $code, @args) = @_; 546 my ($self, $code, @args) = @_;
502 547
503 $self->_cmd (e => $code, @args); 548 $self->_cmd (e => pack "(w/a*)*", $code, @args);
504 549
505 $self 550 $self
506} 551}
507 552
508=item $proc = $proc->require ($module, ...) 553=item $proc = $proc->require ($module, ...)
568=cut 613=cut
569 614
570sub send_arg { 615sub send_arg {
571 my ($self, @arg) = @_; 616 my ($self, @arg) = @_;
572 617
573 $self->_cmd (a => @arg); 618 $self->_cmd (a => pack "(w/a*)*", @arg);
574 619
575 $self 620 $self
576} 621}
577 622
578=item $proc->run ($func, $cb->($fh)) 623=item $proc->run ($func, $cb->($fh))
579 624
580Enter the function specified by the fully qualified name in C<$func> in 625Enter the function specified by the function name in C<$func> in the
581the process. The function is called with the communication socket as first 626process. The function is called with the communication socket as first
582argument, followed by all file handles and string arguments sent earlier 627argument, followed by all file handles and string arguments sent earlier
583via C<send_fh> and C<send_arg> methods, in the order they were called. 628via C<send_fh> and C<send_arg> methods, in the order they were called.
584 629
585If the called function returns, the process exits. 630The function name should be fully qualified, but if it isn't, it will be
631looked up in the main package.
586 632
587Preparing the process can take time - when the process is ready, the 633If the called function returns, doesn't exist, or any error occurs, the
634process exits.
635
636Preparing the process is done in the background - when all commands have
588callback is invoked with the local communications socket as argument. 637been 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
639like.
589 640
590The process object becomes unusable on return from this function. 641The process object becomes unusable on return from this function - any
642further method calls result in undefined behaviour.
591 643
592If the communication socket isn't used, it should be closed on both sides, 644If the communication socket isn't used, it should be closed on both sides,
593to save on kernel memory. 645to save on kernel memory.
594 646
595The socket is non-blocking in the parent, and blocking in the newly 647The socket is non-blocking in the parent, and blocking in the newly
596created process. The close-on-exec flag is set on both. Even if not used 648created process. The close-on-exec flag is set in both.
649
597otherwise, the socket can be a good indicator for the existence of the 650Even if not used otherwise, the socket can be a good indicator for the
598process - if the other process exits, you get a readable event on it, 651existence of the process - if the other process exits, you get a readable
599because exiting the process closes the socket (if it didn't create any 652event on it, because exiting the process closes the socket (if it didn't
600children using fork). 653create any children using fork).
601 654
602Example: create a template for a process pool, pass a few strings, some 655Example: create a template for a process pool, pass a few strings, some
603file handles, then fork, pass one more string, and run some code. 656file handles, then fork, pass one more string, and run some code.
604 657
605 my $pool = AnyEvent::Fork 658 my $pool = AnyEvent::Fork
613 ->send_arg ("str3") 666 ->send_arg ("str3")
614 ->run ("Some::function", sub { 667 ->run ("Some::function", sub {
615 my ($fh) = @_; 668 my ($fh) = @_;
616 669
617 # fh is nonblocking, but we trust that the OS can accept these 670 # fh is nonblocking, but we trust that the OS can accept these
618 # extra 3 octets anyway. 671 # few octets anyway.
619 syswrite $fh, "hi #$_\n"; 672 syswrite $fh, "hi #$_\n";
620 673
621 # $fh is being closed here, as we don't store it anywhere 674 # $fh is being closed here, as we don't store it anywhere
622 }); 675 });
623 } 676 }
625 # Some::function might look like this - all parameters passed before fork 678 # Some::function might look like this - all parameters passed before fork
626 # and after will be passed, in order, after the communications socket. 679 # and after will be passed, in order, after the communications socket.
627 sub Some::function { 680 sub Some::function {
628 my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_; 681 my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_;
629 682
630 print scalar <$fh>; # prints "hi 1\n" and "hi 2\n" 683 print scalar <$fh>; # prints "hi #1\n" and "hi #2\n" in any order
631 } 684 }
632 685
633=cut 686=cut
634 687
635sub run { 688sub run {
636 my ($self, $func, $cb) = @_; 689 my ($self, $func, $cb) = @_;
637 690
638 $self->[0] = $cb; 691 $self->[4] = $cb;
639 $self->_cmd (r => $func); 692 $self->_cmd (r => $func);
640} 693}
641 694
642=back 695=back
643 696
690This section lists typical problems that remain. I hope by recognising 743This section lists typical problems that remain. I hope by recognising
691them, most can be avoided. 744them, most can be avoided.
692 745
693=over 4 746=over 4
694 747
695=item exit runs destructors
696
697=item "leaked" file descriptors for exec'ed processes 748=item "leaked" file descriptors for exec'ed processes
698 749
699POSIX systems inherit file descriptors by default when exec'ing a new 750POSIX systems inherit file descriptors by default when exec'ing a new
700process. While perl itself laudably sets the close-on-exec flags on new 751process. While perl itself laudably sets the close-on-exec flags on new
701file handles, most C libraries don't care, and even if all cared, it's 752file handles, most C libraries don't care, and even if all cared, it's
741 792
742The solution is to either not load these modules before use'ing 793The solution is to either not load these modules before use'ing
743L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay 794L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay
744initialising them, for example, by calling C<init Gtk2> manually. 795initialising them, for example, by calling C<init Gtk2> manually.
745 796
797=item exit runs destructors
798
799This only applies to users of Lc<AnyEvent::Fork:Early> and
800L<AnyEvent::Fork::Template>.
801
802When a process created by AnyEvent::Fork exits, it might do so by calling
803exit, or simply letting perl reach the end of the program. At which point
804Perl runs all destructors.
805
806Not all destructors are fork-safe - for example, an object that represents
807the connection to an X display might tell the X server to free resources,
808which is inconvenient when the "real" object in the parent still needs to
809use them.
810
811This is obviously not a problem for L<AnyEvent::Fork::Early>, as you used
812it as the very first thing, right?
813
814It is a problem for L<AnyEvent::Fork::Template> though - and the solution
815is to not create objects with nontrivial destructors that might have an
816effect outside of Perl.
817
746=back 818=back
747 819
748=head1 PORTABILITY NOTES 820=head1 PORTABILITY NOTES
749 821
750Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop, 822Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop,

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines