… | |
… | |
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 | |
68 | This module allows you to create new processes, without actually forking |
96 | This module allows you to create new processes, without actually forking |
69 | them from your current process (avoiding the problems of forking), but |
97 | them from your current process (avoiding the problems of forking), but |
70 | preserving most of the advantages of fork. |
98 | preserving most of the advantages of fork. |
… | |
… | |
251 | |
279 | |
252 | package AnyEvent::Fork; |
280 | package AnyEvent::Fork; |
253 | |
281 | |
254 | use common::sense; |
282 | use common::sense; |
255 | |
283 | |
256 | use Socket (); |
284 | use Errno (); |
257 | |
285 | |
258 | use AnyEvent; |
286 | use AnyEvent; |
259 | use AnyEvent::Util (); |
287 | use AnyEvent::Util (); |
260 | |
288 | |
261 | use IO::FDPass; |
289 | use IO::FDPass; |
262 | |
290 | |
263 | our $VERSION = 0.2; |
291 | our $VERSION = 0.5; |
264 | |
292 | |
265 | our $PERL; # the path to the perl interpreter, deduces with various forms of magic |
293 | our $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 | |
… | |
… | |
281 | our $TEMPLATE; |
309 | our $TEMPLATE; |
282 | |
310 | |
283 | sub _cmd { |
311 | sub _cmd { |
284 | my $self = shift; |
312 | my $self = shift; |
285 | |
313 | |
286 | #TODO: maybe append the packet to any existing string command already in the queue |
|
|
287 | |
|
|
288 | # ideally, we would want to use "a (w/a)*" as format string, but perl versions |
314 | # ideally, we would want to use "a (w/a)*" as format string, but perl |
289 | # from at least 5.8.9 to 5.16.3 are all buggy and can't unpack it. |
315 | # versions from at least 5.8.9 to 5.16.3 are all buggy and can't unpack |
|
|
316 | # it. |
290 | push @{ $self->[2] }, pack "L/a*", pack "(w/a*)*", @_; |
317 | push @{ $self->[2] }, pack "a L/a*", $_[0], $_[1]; |
291 | |
318 | |
292 | $self->[3] ||= AE::io $self->[1], 1, sub { |
319 | $self->[3] ||= AE::io $self->[1], 1, sub { |
|
|
320 | do { |
293 | # 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, |
294 | # or a plain string. |
322 | # or a plain string. |
295 | |
323 | |
296 | if (ref $self->[2][0]) { |
324 | if (ref $self->[2][0]) { |
297 | # send fh |
325 | # send fh |
298 | IO::FDPass::send fileno $self->[1], fileno ${ $self->[2][0] } |
326 | unless (IO::FDPass::send fileno $self->[1], fileno ${ $self->[2][0] }) { |
|
|
327 | return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK; |
|
|
328 | undef $self->[3]; |
|
|
329 | die "AnyEvent::Fork: file descriptor send failure: $!"; |
|
|
330 | } |
|
|
331 | |
299 | and shift @{ $self->[2] }; |
332 | shift @{ $self->[2] }; |
300 | |
333 | |
301 | } else { |
334 | } else { |
302 | # send string |
335 | # send string |
303 | my $len = syswrite $self->[1], $self->[2][0] |
336 | my $len = syswrite $self->[1], $self->[2][0]; |
|
|
337 | |
|
|
338 | unless ($len) { |
|
|
339 | return if $! == Errno::EAGAIN || $! == Errno::EWOULDBLOCK; |
|
|
340 | undef $self->[3]; |
304 | or do { undef $self->[3]; die "AnyEvent::Fork: command write failure: $!" }; |
341 | die "AnyEvent::Fork: command write failure: $!"; |
|
|
342 | } |
305 | |
343 | |
306 | substr $self->[2][0], 0, $len, ""; |
344 | substr $self->[2][0], 0, $len, ""; |
307 | shift @{ $self->[2] } unless length $self->[2][0]; |
345 | shift @{ $self->[2] } unless length $self->[2][0]; |
308 | } |
346 | } |
|
|
347 | } while @{ $self->[2] }; |
309 | |
348 | |
310 | unless (@{ $self->[2] }) { |
349 | # everything written |
311 | undef $self->[3]; |
350 | undef $self->[3]; |
|
|
351 | |
312 | # invoke run callback |
352 | # invoke run callback, if any |
313 | $self->[0]->($self->[1]) if $self->[0]; |
353 | $self->[4]->($self->[1]) if $self->[4]; |
314 | } |
|
|
315 | }; |
354 | }; |
316 | |
355 | |
317 | () # make sure we don't leak the watcher |
356 | () # make sure we don't leak the watcher |
318 | } |
357 | } |
319 | |
358 | |
320 | sub _new { |
359 | sub _new { |
321 | my ($self, $fh) = @_; |
360 | my ($self, $fh, $pid) = @_; |
322 | |
361 | |
323 | AnyEvent::Util::fh_nonblocking $fh, 1; |
362 | AnyEvent::Util::fh_nonblocking $fh, 1; |
324 | |
363 | |
325 | $self = bless [ |
364 | $self = bless [ |
326 | undef, # run callback |
365 | $pid, |
327 | $fh, |
366 | $fh, |
328 | [], # write queue - strings or fd's |
367 | [], # write queue - strings or fd's |
329 | undef, # AE watcher |
368 | undef, # AE watcher |
330 | ], $self; |
369 | ], $self; |
331 | |
370 | |
… | |
… | |
349 | exit 0; |
388 | exit 0; |
350 | } elsif (!$pid) { |
389 | } elsif (!$pid) { |
351 | die "AnyEvent::Fork::Early/Template: unable to fork template process: $!"; |
390 | die "AnyEvent::Fork::Early/Template: unable to fork template process: $!"; |
352 | } |
391 | } |
353 | |
392 | |
354 | AnyEvent::Fork->_new ($fh) |
393 | AnyEvent::Fork->_new ($fh, $pid) |
355 | } |
394 | } |
356 | |
395 | |
357 | =item my $proc = new AnyEvent::Fork |
396 | =item my $proc = new AnyEvent::Fork |
358 | |
397 | |
359 | Create a new "empty" perl interpreter process and returns its process |
398 | Create a new "empty" perl interpreter process and returns its process |
… | |
… | |
452 | # 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 |
453 | #local $ENV{PERL5LIB} = join ":", grep !ref, @INC; |
492 | #local $ENV{PERL5LIB} = join ":", grep !ref, @INC; |
454 | my %env = %ENV; |
493 | my %env = %ENV; |
455 | $env{PERL5LIB} = join +($^O eq "MSWin32" ? ";" : ":"), grep !ref, @INC; |
494 | $env{PERL5LIB} = join +($^O eq "MSWin32" ? ";" : ":"), grep !ref, @INC; |
456 | |
495 | |
457 | Proc::FastSpawn::spawn ( |
496 | my $pid = Proc::FastSpawn::spawn ( |
458 | $perl, |
497 | $perl, |
459 | ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$], |
498 | ["perl", "-MAnyEvent::Fork::Serve", "-e", "AnyEvent::Fork::Serve::me", fileno $slave, $$], |
460 | [map "$_=$env{$_}", keys %env], |
499 | [map "$_=$env{$_}", keys %env], |
461 | ) or die "unable to spawn AnyEvent::Fork server: $!"; |
500 | ) or die "unable to spawn AnyEvent::Fork server: $!"; |
462 | |
501 | |
463 | $self->_new ($fh) |
502 | $self->_new ($fh, $pid) |
|
|
503 | } |
|
|
504 | |
|
|
505 | =item $pid = $proc->pid |
|
|
506 | |
|
|
507 | Returns the process id of the process I<iff it is a direct child of the |
|
|
508 | process> running AnyEvent::Fork, and C<undef> otherwise. |
|
|
509 | |
|
|
510 | Normally, only processes created via C<< AnyEvent::Fork->new_exec >> and |
|
|
511 | L<AnyEvent::Fork::Template> are direct children, and you are responsible |
|
|
512 | to clean up their zombies when they die. |
|
|
513 | |
|
|
514 | All other processes are not direct children, and will be cleaned up by |
|
|
515 | AnyEvent::Fork. |
|
|
516 | |
|
|
517 | =cut |
|
|
518 | |
|
|
519 | sub pid { |
|
|
520 | $_[0][0] |
464 | } |
521 | } |
465 | |
522 | |
466 | =item $proc = $proc->eval ($perlcode, @args) |
523 | =item $proc = $proc->eval ($perlcode, @args) |
467 | |
524 | |
468 | Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to |
525 | Evaluates the given C<$perlcode> as ... perl code, while setting C<@_> to |
469 | the strings specified by C<@args>. |
526 | the strings specified by C<@args>, in the "main" package. |
470 | |
527 | |
471 | This call is meant to do any custom initialisation that might be required |
528 | This call is meant to do any custom initialisation that might be required |
472 | (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 |
473 | to completely take over the process, use C<run> for that. |
530 | to completely take over the process, use C<run> for that. |
474 | |
531 | |
475 | The code will usually be executed after this call returns, and there is no |
532 | The code will usually be executed after this call returns, and there is no |
476 | way to pass anything back to the calling process. Any evaluation errors |
533 | way to pass anything back to the calling process. Any evaluation errors |
477 | will be reported to stderr and cause the process to exit. |
534 | will be reported to stderr and cause the process to exit. |
478 | |
535 | |
|
|
536 | If 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 |
|
|
538 | C<eval> first, and then call it via C<run>. This also gives you access to |
|
|
539 | any arguments passed via the C<send_xxx> methods, such as file handles. |
|
|
540 | |
479 | Returns the process object for easy chaining of method calls. |
541 | Returns the process object for easy chaining of method calls. |
480 | |
542 | |
481 | =cut |
543 | =cut |
482 | |
544 | |
483 | sub eval { |
545 | sub eval { |
484 | my ($self, $code, @args) = @_; |
546 | my ($self, $code, @args) = @_; |
485 | |
547 | |
486 | $self->_cmd (e => $code, @args); |
548 | $self->_cmd (e => pack "(w/a*)*", $code, @args); |
487 | |
549 | |
488 | $self |
550 | $self |
489 | } |
551 | } |
490 | |
552 | |
491 | =item $proc = $proc->require ($module, ...) |
553 | =item $proc = $proc->require ($module, ...) |
… | |
… | |
539 | =item $proc = $proc->send_arg ($string, ...) |
601 | =item $proc = $proc->send_arg ($string, ...) |
540 | |
602 | |
541 | Send one or more argument strings to the process, to prepare a call to |
603 | Send one or more argument strings to the process, to prepare a call to |
542 | C<run>. The strings can be any octet string. |
604 | C<run>. The strings can be any octet string. |
543 | |
605 | |
|
|
606 | The protocol is optimised to pass a moderate number of relatively short |
|
|
607 | strings - while you can pass up to 4GB of data in one go, this is more |
|
|
608 | meant to pass some ID information or other startup info, not big chunks of |
|
|
609 | data. |
|
|
610 | |
544 | Returns the process object for easy chaining of method calls. |
611 | Returns the process object for easy chaining of method calls. |
545 | |
612 | |
546 | =cut |
613 | =cut |
547 | |
614 | |
548 | sub send_arg { |
615 | sub send_arg { |
549 | my ($self, @arg) = @_; |
616 | my ($self, @arg) = @_; |
550 | |
617 | |
551 | $self->_cmd (a => @arg); |
618 | $self->_cmd (a => pack "(w/a*)*", @arg); |
552 | |
619 | |
553 | $self |
620 | $self |
554 | } |
621 | } |
555 | |
622 | |
556 | =item $proc->run ($func, $cb->($fh)) |
623 | =item $proc->run ($func, $cb->($fh)) |
557 | |
624 | |
558 | Enter the function specified by the fully qualified name in C<$func> in |
625 | Enter the function specified by the function name in C<$func> in the |
559 | the process. The function is called with the communication socket as first |
626 | process. The function is called with the communication socket as first |
560 | argument, followed by all file handles and string arguments sent earlier |
627 | argument, followed by all file handles and string arguments sent earlier |
561 | via C<send_fh> and C<send_arg> methods, in the order they were called. |
628 | via C<send_fh> and C<send_arg> methods, in the order they were called. |
562 | |
629 | |
563 | If the called function returns, the process exits. |
630 | The function name should be fully qualified, but if it isn't, it will be |
|
|
631 | looked up in the main package. |
564 | |
632 | |
565 | Preparing the process can take time - when the process is ready, the |
633 | If the called function returns, doesn't exist, or any error occurs, the |
|
|
634 | process exits. |
|
|
635 | |
|
|
636 | Preparing the process is done in the background - when all commands have |
566 | callback is invoked with the local communications socket as argument. |
637 | been sent, the callback is invoked with the local communications socket |
|
|
638 | as argument. At this point you can start using the socket in any way you |
|
|
639 | like. |
567 | |
640 | |
568 | The process object becomes unusable on return from this function. |
641 | The process object becomes unusable on return from this function - any |
|
|
642 | further method calls result in undefined behaviour. |
569 | |
643 | |
570 | If the communication socket isn't used, it should be closed on both sides, |
644 | If the communication socket isn't used, it should be closed on both sides, |
571 | to save on kernel memory. |
645 | to save on kernel memory. |
572 | |
646 | |
573 | The socket is non-blocking in the parent, and blocking in the newly |
647 | The socket is non-blocking in the parent, and blocking in the newly |
574 | created process. The close-on-exec flag is set on both. Even if not used |
648 | created process. The close-on-exec flag is set in both. |
|
|
649 | |
575 | otherwise, the socket can be a good indicator for the existence of the |
650 | Even if not used otherwise, the socket can be a good indicator for the |
576 | process - if the other process exits, you get a readable event on it, |
651 | existence of the process - if the other process exits, you get a readable |
577 | because exiting the process closes the socket (if it didn't create any |
652 | event on it, because exiting the process closes the socket (if it didn't |
578 | children using fork). |
653 | create any children using fork). |
579 | |
654 | |
580 | Example: create a template for a process pool, pass a few strings, some |
655 | Example: create a template for a process pool, pass a few strings, some |
581 | file handles, then fork, pass one more string, and run some code. |
656 | file handles, then fork, pass one more string, and run some code. |
582 | |
657 | |
583 | my $pool = AnyEvent::Fork |
658 | my $pool = AnyEvent::Fork |
… | |
… | |
591 | ->send_arg ("str3") |
666 | ->send_arg ("str3") |
592 | ->run ("Some::function", sub { |
667 | ->run ("Some::function", sub { |
593 | my ($fh) = @_; |
668 | my ($fh) = @_; |
594 | |
669 | |
595 | # 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 |
596 | # extra 3 octets anyway. |
671 | # few octets anyway. |
597 | syswrite $fh, "hi #$_\n"; |
672 | syswrite $fh, "hi #$_\n"; |
598 | |
673 | |
599 | # $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 |
600 | }); |
675 | }); |
601 | } |
676 | } |
… | |
… | |
603 | # Some::function might look like this - all parameters passed before fork |
678 | # Some::function might look like this - all parameters passed before fork |
604 | # and after will be passed, in order, after the communications socket. |
679 | # and after will be passed, in order, after the communications socket. |
605 | sub Some::function { |
680 | sub Some::function { |
606 | my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_; |
681 | my ($fh, $str1, $str2, $fh1, $fh2, $str3) = @_; |
607 | |
682 | |
608 | 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 |
609 | } |
684 | } |
610 | |
685 | |
611 | =cut |
686 | =cut |
612 | |
687 | |
613 | sub run { |
688 | sub run { |
614 | my ($self, $func, $cb) = @_; |
689 | my ($self, $func, $cb) = @_; |
615 | |
690 | |
616 | $self->[0] = $cb; |
691 | $self->[4] = $cb; |
617 | $self->_cmd (r => $func); |
692 | $self->_cmd (r => $func); |
618 | } |
693 | } |
619 | |
694 | |
620 | =back |
695 | =back |
621 | |
696 | |
622 | =head1 PERFORMANCE |
697 | =head1 PERFORMANCE |
623 | |
698 | |
624 | Now for some unscientific benchmark numbers (all done on an amd64 |
699 | Now for some unscientific benchmark numbers (all done on an amd64 |
625 | GNU/Linux box). These are intended to give you an idea of the relative |
700 | GNU/Linux box). These are intended to give you an idea of the relative |
626 | performance you can expect. |
701 | performance you can expect, they are not meant to be absolute performance |
|
|
702 | numbers. |
627 | |
703 | |
628 | OK, so, I ran a simple benchmark that creates a socket pair, forks, calls |
704 | OK, so, I ran a simple benchmark that creates a socket pair, forks, calls |
629 | exit in the child and waits for the socket to close in the parent. I did |
705 | exit in the child and waits for the socket to close in the parent. I did |
630 | load AnyEvent, EV and AnyEvent::Fork, for a total process size of 6312kB. |
706 | load AnyEvent, EV and AnyEvent::Fork, for a total process size of 5100kB. |
631 | |
707 | |
632 | 2079 new processes per second, using socketpair + fork manually |
708 | 2079 new processes per second, using manual socketpair + fork |
633 | |
709 | |
634 | Then I did the same thing, but instead of calling fork, I called |
710 | Then I did the same thing, but instead of calling fork, I called |
635 | AnyEvent::Fork->new->run ("CORE::exit") and then again waited for the |
711 | AnyEvent::Fork->new->run ("CORE::exit") and then again waited for the |
636 | socket form the child to close on exit. This does the same thing as manual |
712 | socket form the child to close on exit. This does the same thing as manual |
637 | socket pair + fork, except that what is forked is the template process |
713 | socket pair + fork, except that what is forked is the template process |
… | |
… | |
667 | This section lists typical problems that remain. I hope by recognising |
743 | This section lists typical problems that remain. I hope by recognising |
668 | them, most can be avoided. |
744 | them, most can be avoided. |
669 | |
745 | |
670 | =over 4 |
746 | =over 4 |
671 | |
747 | |
672 | =item exit runs destructors |
|
|
673 | |
|
|
674 | =item "leaked" file descriptors for exec'ed processes |
748 | =item "leaked" file descriptors for exec'ed processes |
675 | |
749 | |
676 | POSIX systems inherit file descriptors by default when exec'ing a new |
750 | POSIX systems inherit file descriptors by default when exec'ing a new |
677 | process. While perl itself laudably sets the close-on-exec flags on new |
751 | process. While perl itself laudably sets the close-on-exec flags on new |
678 | file handles, most C libraries don't care, and even if all cared, it's |
752 | file handles, most C libraries don't care, and even if all cared, it's |
… | |
… | |
718 | |
792 | |
719 | The solution is to either not load these modules before use'ing |
793 | The solution is to either not load these modules before use'ing |
720 | L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay |
794 | L<AnyEvent::Fork::Early> or L<AnyEvent::Fork::Template>, or to delay |
721 | initialising them, for example, by calling C<init Gtk2> manually. |
795 | initialising them, for example, by calling C<init Gtk2> manually. |
722 | |
796 | |
|
|
797 | =item exit runs destructors |
|
|
798 | |
|
|
799 | This only applies to users of Lc<AnyEvent::Fork:Early> and |
|
|
800 | L<AnyEvent::Fork::Template>. |
|
|
801 | |
|
|
802 | When a process created by AnyEvent::Fork exits, it might do so by calling |
|
|
803 | exit, or simply letting perl reach the end of the program. At which point |
|
|
804 | Perl runs all destructors. |
|
|
805 | |
|
|
806 | Not all destructors are fork-safe - for example, an object that represents |
|
|
807 | the connection to an X display might tell the X server to free resources, |
|
|
808 | which is inconvenient when the "real" object in the parent still needs to |
|
|
809 | use them. |
|
|
810 | |
|
|
811 | This is obviously not a problem for L<AnyEvent::Fork::Early>, as you used |
|
|
812 | it as the very first thing, right? |
|
|
813 | |
|
|
814 | It is a problem for L<AnyEvent::Fork::Template> though - and the solution |
|
|
815 | is to not create objects with nontrivial destructors that might have an |
|
|
816 | effect outside of Perl. |
|
|
817 | |
723 | =back |
818 | =back |
724 | |
819 | |
725 | =head1 PORTABILITY NOTES |
820 | =head1 PORTABILITY NOTES |
726 | |
821 | |
727 | Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop, |
822 | Native win32 perls are somewhat supported (AnyEvent::Fork::Early is a nop, |