AnyEvent-Fork

 view release on metacpan or  search on metacpan

README  view on Meta::CPAN


       # create a pool template, initialise it and give it the socket
       my $pool = AnyEvent::Fork
                     ->new
                     ->require ("Some::Stuff", "My::Server")
                     ->send_fh ($listener);

       # now create 10 identical workers
       for my $id (1..10) {
          $pool
             ->fork
             ->send_arg ($id)
             ->run ("My::Server::run");
       }

       # now do other things - maybe use the filehandle provided by run
       # to wait for the processes to die. or whatever.

    "My::Server" might look like this:

       package My::Server;

       sub run {
          my ($slave, $listener, $id) = @_;

          close $slave; # we do not use the socket, so close it to save resources

          # we could go ballistic and use e.g. AnyEvent here, or IO::AIO,
          # or anything we usually couldn't do in a process forked normally.
          while (my $socket = $listener->accept) {
             # do sth. with new socket
          }
       }

  use AnyEvent::Fork as a faster fork+exec
    This runs "/bin/echo hi", with standard output redirected to /tmp/log
    and standard error redirected to the communications socket. It is
    usually faster than fork+exec, but still lets you prepare the
    environment.

       open my $output, ">/tmp/log" or die "$!";

       AnyEvent::Fork
          ->new
          ->eval ('
               # compile a helper function for later use
               sub run {
                  my ($fh, $output, @cmd) = @_;

                  # perl will clear close-on-exec on STDOUT/STDERR
                  open STDOUT, ">&", $output or die;
                  open STDERR, ">&", $fh or die;

                  exec @cmd;
               }
            ')
          ->send_fh ($output)
          ->send_arg ("/bin/echo", "hi")
          ->run ("run", my $cv = AE::cv);

       my $stderr = $cv->recv;

  For stingy users: put the worker code into a "DATA" section.
    When you want to be stingy with files, you can put your code into the
    "DATA" section of your module (or program):

       use AnyEvent::Fork;

       AnyEvent::Fork
          ->new
          ->eval (do { local $/; <DATA> })
          ->run ("doit", sub { ... });

       __DATA__

       sub doit {
          ... do something!
       }

  For stingy standalone programs: do not rely on external files at
all.
    For single-file scripts it can be inconvenient to rely on external files
    - even when using a "DATA" section, you still need to "exec" an external
    perl interpreter, which might not be available when using
    App::Staticperl, Urlader or PAR::Packer for example.

    Two modules help here - AnyEvent::Fork::Early forks a template process
    for all further calls to "new_exec", and AnyEvent::Fork::Template forks
    the main program as a template process.

    Here is how your main program should look like:

       #! perl

       # optional, as the very first thing.
       # in case modules want to create their own processes.
       use AnyEvent::Fork::Early;

       # next, load all modules you need in your template process
       use Example::My::Module
       use Example::Whatever;

       # next, put your run function definition and anything else you
       # need, but do not use code outside of BEGIN blocks.
       sub worker_run {
          my ($fh, @args) = @_;
          ...
       }

       # now preserve everything so far as AnyEvent::Fork object
       # in $TEMPLATE.
       use AnyEvent::Fork::Template;

       # do not put code outside of BEGIN blocks until here

       # now use the $TEMPLATE process in any way you like

       # for example: create 10 worker processes
       my @worker;
       my $cv = AE::cv;
       for (1..10) {

README  view on Meta::CPAN

        The new process is forked from a template process that is kept
        around for this purpose. When it doesn't exist yet, it is created by
        a call to "new_exec" first and then stays around for future calls.

    $new_proc = $proc->fork
        Forks $proc, creating a new process, and returns the process object
        of the new process.

        If any of the "send_" functions have been called before fork, then
        they will be cloned in the child. For example, in a pre-forked
        server, you might "send_fh" the listening socket into the template
        process, and then keep calling "fork" and "run".

    my $proc = new_exec AnyEvent::Fork
        Create a new "empty" perl interpreter process and returns its
        process object for further manipulation.

        Unlike the "new" method, this method *always* spawns a new perl
        process (except in some cases, see AnyEvent::Fork::Early for
        details). This reduces the amount of memory sharing that is
        possible, and is also slower.

        You should use "new" whenever possible, except when having a
        template process around is unacceptable.

        The path to the perl interpreter is divined using various methods -
        first $^X is investigated to see if the path ends with something
        that looks as if it were the perl interpreter. Failing this, the
        module falls back to using $Config::Config{perlpath}.

        The path to perl can also be overridden by setting the global
        variable $AnyEvent::Fork::PERL - it's value will be used for all
        subsequent invocations.

    $pid = $proc->pid
        Returns the process id of the process *iff it is a direct child of
        the process running AnyEvent::Fork*, and "undef" otherwise. As a
        general rule (that you cannot rely upon), processes created via
        "new_exec", AnyEvent::Fork::Early or AnyEvent::Fork::Template are
        direct children, while all other processes are not.

        Or in other words, you do not normally have to take care of zombies
        for processes created via "new", but when in doubt, or zombies are a
        problem, you need to check whether a process is a diretc child by
        calling this method, and possibly creating a child watcher or reap
        it manually.

    $proc = $proc->eval ($perlcode, @args)
        Evaluates the given $perlcode as ... Perl code, while setting @_ to
        the strings specified by @args, in the "main" package (so you can
        access the args using $_[0] and so on, but not using implicit "shit"
        as the latter works on @ARGV).

        This call is meant to do any custom initialisation that might be
        required (for example, the "require" method uses it). It's not
        supposed to be used to completely take over the process, use "run"
        for that.

        The code will usually be executed after this call returns, and there
        is no way to pass anything back to the calling process. Any
        evaluation errors will be reported to stderr and cause the process
        to exit.

        If you want to execute some code (that isn't in a module) to take
        over the process, you should compile a function via "eval" first,
        and then call it via "run". This also gives you access to any
        arguments passed via the "send_xxx" methods, such as file handles.
        See the "use AnyEvent::Fork as a faster fork+exec" example to see it
        in action.

        Returns the process object for easy chaining of method calls.

        It's common to want to call an iniitalisation function with some
        arguments. Make sure you actually pass @_ to that function (for
        example by using &name syntax), and do not just specify a function
        name:

           $proc->eval ('&MyModule::init', $string1, $string2);

    $proc = $proc->require ($module, ...)
        Tries to load the given module(s) into the process

        Returns the process object for easy chaining of method calls.

    $proc = $proc->send_fh ($handle, ...)
        Send one or more file handles (*not* file descriptors) to the
        process, to prepare a call to "run".

        The process object keeps a reference to the handles until they have
        been passed over to the process, so you must not explicitly close
        the handles. This is most easily accomplished by simply not storing
        the file handles anywhere after passing them to this method - when
        AnyEvent::Fork is finished using them, perl will automatically close
        them.

        Returns the process object for easy chaining of method calls.

        Example: pass a file handle to a process, and release it without
        closing. It will be closed automatically when it is no longer used.

           $proc->send_fh ($my_fh);
           undef $my_fh; # free the reference if you want, but DO NOT CLOSE IT

    $proc = $proc->send_arg ($string, ...)
        Send one or more argument strings to the process, to prepare a call
        to "run". The strings can be any octet strings.

        The protocol is optimised to pass a moderate number of relatively
        short strings - while you can pass up to 4GB of data in one go, this
        is more meant to pass some ID information or other startup info, not
        big chunks of data.

        Returns the process object for easy chaining of method calls.

    $proc->run ($func, $cb->($fh))
        Enter the function specified by the function name in $func in the
        process. The function is called with the communication socket as
        first argument, followed by all file handles and string arguments
        sent earlier via "send_fh" and "send_arg" methods, in the order they
        were called.



( run in 3.186 seconds using v1.01-cache-2.11-cpan-5837b0d9d2c )