0x1949 Team - FAZEMRX - MANAGER
Edit File: Parallel::ForkManager.3pm
.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Parallel::ForkManager 3pm" .TH Parallel::ForkManager 3pm "2024-08-24" "perl v5.34.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Parallel::ForkManager \- A simple parallel processing fork manager .SH "VERSION" .IX Header "VERSION" version 2.03 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use Parallel::ForkManager; \& \& my $pm = Parallel::ForkManager\->new($MAX_PROCESSES); \& \& DATA_LOOP: \& foreach my $data (@all_data) { \& # Forks and returns the pid for the child: \& my $pid = $pm\->start and next DATA_LOOP; \& \& ... do some work with $data in the child process ... \& \& $pm\->finish; # Terminates the child process \& } .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module is intended for use in operations that can be done in parallel where the number of processes to be forked off should be limited. Typical use is a downloader which will be retrieving hundreds/thousands of files. .PP The code for a downloader would look something like this: .PP .Vb 2 \& use LWP::Simple; \& use Parallel::ForkManager; \& \& ... \& \& my @links=( \& ["http://www.foo.bar/rulez.data","rulez_data.txt"], \& ["http://new.host/more_data.doc","more_data.doc"], \& ... \& ); \& \& ... \& \& # Max 30 processes for parallel download \& my $pm = Parallel::ForkManager\->new(30); \& \& LINKS: \& foreach my $linkarray (@links) { \& $pm\->start and next LINKS; # do the fork \& \& my ($link, $fn) = @$linkarray; \& warn "Cannot get $fn from $link" \& if getstore($link, $fn) != RC_OK; \& \& $pm\->finish; # do the exit in the child process \& } \& $pm\->wait_all_children; .Ve .PP First you need to instantiate the ForkManager with the \*(L"new\*(R" constructor. You must specify the maximum number of processes to be created. If you specify 0, then \s-1NO\s0 fork will be done; this is good for debugging purposes. .PP Next, use \f(CW$pm\fR\->start to do the fork. \f(CW$pm\fR returns 0 for the child process, and child pid for the parent process (see also \*(L"fork\*(R" in perlfunc). The \*(L"and next\*(R" skips the internal loop in the parent process. \s-1NOTE:\s0 \&\f(CW$pm\fR\->start dies if the fork fails. .PP \&\f(CW$pm\fR\->finish terminates the child process (assuming a fork was done in the \&\*(L"start\*(R"). .PP \&\s-1NOTE:\s0 You cannot use \f(CW$pm\fR\->start if you are already in the child process. If you want to manage another set of subprocesses in the child process, you must instantiate another Parallel::ForkManager object! .SH "METHODS" .IX Header "METHODS" The comment letter indicates where the method should be run. P for parent, C for child. .ie n .IP "new $processes" 5 .el .IP "new \f(CW$processes\fR" 5 .IX Item "new $processes" Instantiate a new Parallel::ForkManager object. You must specify the maximum number of children to fork off. If you specify 0 (zero), then no children will be forked. This is intended for debugging purposes. .Sp The optional second parameter, \f(CW$tempdir\fR, is only used if you want the children to send back a reference to some data (see \s-1RETRIEVING DATASTRUCTURES\s0 below). If not provided, it is set via a call to File::Temp::\fBtempdir()\fR. .Sp The new method will die if the temporary directory does not exist or it is not a directory. .Sp Since version 2.00, the constructor can also be called in the typical Moo/Moose fashion. I.e. .Sp .Vb 5 \& my $fm = Parallel::ForkManager\->new( \& max_proc => 4, \& tempdir => \*(Aq...\*(Aq, \& child_role => \*(AqParallel::ForkManager::CustomChild\*(Aq, \& ); .Ve .IP "child_role" 5 .IX Item "child_role" Returns the name of the role consumed by the ForkManager object in child processes. Defaults to Parallel::ForkManager::Child and can be set to something else via the constructor. .ie n .IP "start [ $process_identifier ]" 5 .el .IP "start [ \f(CW$process_identifier\fR ]" 5 .IX Item "start [ $process_identifier ]" This method does the fork. It returns the pid of the child process for the parent, and 0 for the child process. If the \f(CW$processes\fR parameter for the constructor is 0 then, assuming you're in the child process, \&\f(CW$pm\fR\->start simply returns 0. .Sp An optional \f(CW$process_identifier\fR can be provided to this method... It is used by the \*(L"run_on_finish\*(R" callback (see \s-1CALLBACKS\s0) for identifying the finished process. .ie n .IP "start_child [ $process_identifier, ] \e&callback" 5 .el .IP "start_child [ \f(CW$process_identifier\fR, ] \e&callback" 5 .IX Item "start_child [ $process_identifier, ] &callback" Like \f(CW\*(C`start\*(C'\fR, but will run the \f(CW&callback\fR as the child. If the callback returns anything, it'll be passed as the data to transmit back to the parent process via \f(CW\*(C`finish()\*(C'\fR. .ie n .IP "finish [ $exit_code [, $data_structure_reference] ]" 5 .el .IP "finish [ \f(CW$exit_code\fR [, \f(CW$data_structure_reference\fR] ]" 5 .IX Item "finish [ $exit_code [, $data_structure_reference] ]" Closes the child process by exiting and accepts an optional exit code (default exit code is 0) which can be retrieved in the parent via callback. If the second optional parameter is provided, the child attempts to send its contents back to the parent. If you use the program in debug mode ($processes == 0), this method just calls the callback. .Sp If the \f(CW$data_structure_reference\fR is provided, then it is serialized and passed to the parent process. See \s-1RETRIEVING DATASTRUCTURES\s0 for more info. .ie n .IP "set_max_procs $processes" 5 .el .IP "set_max_procs \f(CW$processes\fR" 5 .IX Item "set_max_procs $processes" Allows you to set a new maximum number of children to maintain. .IP "wait_all_children" 5 .IX Item "wait_all_children" You can call this method to wait for all the processes which have been forked. This is a blocking wait. .IP "reap_finished_children" 5 .IX Item "reap_finished_children" This is a non-blocking call to reap children and execute callbacks independent of calls to \*(L"start\*(R" or \*(L"wait_all_children\*(R". Use this in scenarios where \*(L"start\*(R" is called infrequently but you would like the callbacks executed quickly. .IP "is_parent" 5 .IX Item "is_parent" Returns \f(CW\*(C`true\*(C'\fR if within the parent or \f(CW\*(C`false\*(C'\fR if within the child. .IP "is_child" 5 .IX Item "is_child" Returns \f(CW\*(C`true\*(C'\fR if within the child or \f(CW\*(C`false\*(C'\fR if within the parent. .IP "max_procs" 5 .IX Item "max_procs" Returns the maximal number of processes the object will fork. .IP "running_procs" 5 .IX Item "running_procs" Returns the pids of the forked processes currently monitored by the \&\f(CW\*(C`Parallel::ForkManager\*(C'\fR. Note that children are still reported as running until the fork manager harvest them, via the next call to \&\f(CW\*(C`start\*(C'\fR or \f(CW\*(C`wait_all_children\*(C'\fR. .Sp .Vb 1 \& my @pids = $pm\->running_procs; \& \& my $nbr_children = $pm\->running_procs; .Ve .ie n .IP "wait_for_available_procs( $n )" 5 .el .IP "wait_for_available_procs( \f(CW$n\fR )" 5 .IX Item "wait_for_available_procs( $n )" Wait until \f(CW$n\fR available process slots are available. If \f(CW$n\fR is not given, defaults to \fI1\fR. .IP "waitpid_blocking_sleep" 5 .IX Item "waitpid_blocking_sleep" Returns the sleep period, in seconds, of the pseudo-blocking calls. The sleep period can be a fraction of second. .Sp Returns \f(CW0\fR if disabled. .Sp Defaults to 1 second. .Sp See \fI\s-1BLOCKING CALLS\s0\fR for more details. .ie n .IP "set_waitpid_blocking_sleep $seconds" 5 .el .IP "set_waitpid_blocking_sleep \f(CW$seconds\fR" 5 .IX Item "set_waitpid_blocking_sleep $seconds" Sets the the sleep period, in seconds, of the pseudo-blocking calls. Set to \f(CW0\fR to disable. .Sp See \fI\s-1BLOCKING CALLS\s0\fR for more details. .SH "CALLBACKS" .IX Header "CALLBACKS" You can define callbacks in the code, which are called on events like starting a process or upon finish. Declare these before the first call to \fBstart()\fR. .PP The callbacks can be defined with the following methods: .ie n .IP "run_on_finish $code [, $pid ]" 4 .el .IP "run_on_finish \f(CW$code\fR [, \f(CW$pid\fR ]" 4 .IX Item "run_on_finish $code [, $pid ]" You can define a subroutine which is called when a child is terminated. It is called in the parent process. .Sp The parameters of the \f(CW$code\fR are the following: .Sp .Vb 6 \& \- pid of the process, which is terminated \& \- exit code of the program \& \- identification of the process (if provided in the "start" method) \& \- exit signal (0\-127: signal name) \& \- core dump (1 if there was core dump at exit) \& \- datastructure reference or undef (see RETRIEVING DATASTRUCTURES) .Ve .ie n .IP "run_on_start $code" 4 .el .IP "run_on_start \f(CW$code\fR" 4 .IX Item "run_on_start $code" You can define a subroutine which is called when a child is started. It called after the successful startup of a child in the parent process. .Sp The parameters of the \f(CW$code\fR are the following: .Sp .Vb 2 \& \- pid of the process which has been started \& \- identification of the process (if provided in the "start" method) .Ve .ie n .IP "run_on_wait $code, [$period]" 4 .el .IP "run_on_wait \f(CW$code\fR, [$period]" 4 .IX Item "run_on_wait $code, [$period]" You can define a subroutine which is called when the child process needs to wait for the startup. If \f(CW$period\fR is not defined, then one call is done per child. If \f(CW$period\fR is defined, then \f(CW$code\fR is called periodically and the module waits for \f(CW$period\fR seconds between the two calls. Note, \f(CW$period\fR can be fractional number also. The exact \*(L"$period seconds\*(R" is not guaranteed, signals can shorten and the process scheduler can make it longer (on busy systems). .Sp The \f(CW$code\fR called in the \*(L"start\*(R" and the \*(L"wait_all_children\*(R" method also. .Sp No parameters are passed to the \f(CW$code\fR on the call. .SH "BLOCKING CALLS" .IX Header "BLOCKING CALLS" When it comes to waiting for child processes to terminate, \f(CW\*(C`Parallel::ForkManager\*(C'\fR is between a fork and a hard place (if you excuse the terrible pun). The underlying Perl \f(CW\*(C`waitpid\*(C'\fR function that the module relies on can block until either one specific or any child process terminate, but not for a process part of a given group. .PP This means that the module can do one of two things when it waits for one of its child processes to terminate: .IP "Only wait for its own child processes" 4 .IX Item "Only wait for its own child processes" This is done via a loop using a \f(CW\*(C`waitpid\*(C'\fR non-blocking call and a sleep statement. The code does something along the lines of .Sp .Vb 4 \& while(1) { \& if ( any of the P::FM child process terminated ) { \& return its pid \& } \& \& sleep $sleep_period \& } .Ve .Sp This is the default behavior that the module will use. This is not the most efficient way to wait for child processes, but it's the safest way to ensure that \f(CW\*(C`Parallel::ForkManager\*(C'\fR won't interfere with any other part of the codebase. .Sp The sleep period is set via the method \f(CW\*(C`set_waitpid_blocking_sleep\*(C'\fR. .IP "Block until any process terminate" 4 .IX Item "Block until any process terminate" Alternatively, \f(CW\*(C`Parallel::ForkManager\*(C'\fR can call \f(CW\*(C`waitpid\*(C'\fR such that it will block until any child process terminate. If the child process was not one of the monitored subprocesses, the wait will resume. This is more efficient, but mean that \f(CW\*(C`P::FM\*(C'\fR can captures (and discards) the termination notification that a different part of the code might be waiting for. .Sp If this is a race condition that doesn't apply to your codebase, you can set the \&\fIwaitpid_blocking_sleep\fR period to \f(CW0\fR, which will enable \f(CW\*(C`waitpid\*(C'\fR call blocking. .Sp .Vb 1 \& my $pm = Parallel::ForkManager\->new( 4 ); \& \& $pm\->set_waitpid_blocking_sleep(0); # true blocking calls enabled \& \& for ( 1..100 ) { \& $pm\->start and next; \& \& ...; # do work \& \& $pm\->finish; \& } .Ve .SH "RETRIEVING DATASTRUCTURES from child processes" .IX Header "RETRIEVING DATASTRUCTURES from child processes" The ability for the parent to retrieve data structures is new as of version 0.7.6. .PP Each child process may optionally send 1 data structure back to the parent. By data structure, we mean a reference to a string, hash or array. The contents of the data structure are written out to temporary files on disc using the Storable modules' \fBstore()\fR method. The reference is then retrieved from within the code you send to the run_on_finish callback. .PP The data structure can be any scalar perl data structure which makes sense: string, numeric value or a reference to an array, hash or object. .PP There are 2 steps involved in retrieving data structures: .PP 1) A reference to the data structure the child wishes to send back to the parent is provided as the second argument to the \fBfinish()\fR call. It is up to the child to decide whether or not to send anything back to the parent. .PP 2) The data structure reference is retrieved using the callback provided in the \fBrun_on_finish()\fR method. .PP Keep in mind that data structure retrieval is not the same as returning a data structure from a method call. That is not what actually occurs. The data structure referenced in a given child process is serialized and written out to a file by Storable. The file is subsequently read back into memory and a new data structure belonging to the parent process is created. Please consider the performance penalty it can imply, so try to keep the returned structure small. .SH "EXAMPLES" .IX Header "EXAMPLES" .SS "Parallel get" .IX Subsection "Parallel get" This small example can be used to get URLs in parallel. .PP .Vb 2 \& use Parallel::ForkManager; \& use LWP::Simple; \& \& my $pm = Parallel::ForkManager\->new(10); \& \& LINKS: \& for my $link (@ARGV) { \& $pm\->start and next LINKS; \& my ($fn) = $link =~ /^.*\e/(.*?)$/; \& if (!$fn) { \& warn "Cannot determine filename from $fn\en"; \& } else { \& $0 .= " " . $fn; \& print "Getting $fn from $link\en"; \& my $rc = getstore($link, $fn); \& print "$link downloaded. response code: $rc\en"; \& }; \& $pm\->finish; \& }; .Ve .SS "Callbacks" .IX Subsection "Callbacks" Example of a program using callbacks to get child exit codes: .PP .Vb 2 \& use strict; \& use Parallel::ForkManager; \& \& my $max_procs = 5; \& my @names = qw( Fred Jim Lily Steve Jessica Bob Dave Christine Rico Sara ); \& # hash to resolve PID\*(Aqs back to child specific information \& \& my $pm = Parallel::ForkManager\->new($max_procs); \& \& # Setup a callback for when a child finishes up so we can \& # get it\*(Aqs exit code \& $pm\->run_on_finish( sub { \& my ($pid, $exit_code, $ident) = @_; \& print "** $ident just got out of the pool ". \& "with PID $pid and exit code: $exit_code\en"; \& }); \& \& $pm\->run_on_start( sub { \& my ($pid, $ident)=@_; \& print "** $ident started, pid: $pid\en"; \& }); \& \& $pm\->run_on_wait( sub { \& print "** Have to wait for one children ...\en" \& }, \& 0.5 \& ); \& \& NAMES: \& foreach my $child ( 0 .. $#names ) { \& my $pid = $pm\->start($names[$child]) and next NAMES; \& \& # This code is the child process \& print "This is $names[$child], Child number $child\en"; \& sleep ( 2 * $child ); \& print "$names[$child], Child $child is about to get out...\en"; \& sleep 1; \& $pm\->finish($child); # pass an exit code to finish \& } \& \& print "Waiting for Children...\en"; \& $pm\->wait_all_children; \& print "Everybody is out of the pool!\en"; .Ve .SS "Data structure retrieval" .IX Subsection "Data structure retrieval" In this simple example, each child sends back a string reference. .PP .Vb 2 \& use Parallel::ForkManager 0.7.6; \& use strict; \& \& my $pm = Parallel::ForkManager\->new(2, \*(Aq/server/path/to/temp/dir/\*(Aq); \& \& # data structure retrieval and handling \& $pm \-> run_on_finish ( # called BEFORE the first call to start() \& sub { \& my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_; \& \& # retrieve data structure from child \& if (defined($data_structure_reference)) { # children are not forced to send anything \& my $string = ${$data_structure_reference}; # child passed a string reference \& print "$string\en"; \& } \& else { # problems occurring during storage or retrieval will throw a warning \& print qq|No message received from child process $pid!\en|; \& } \& } \& ); \& \& # prep random statement components \& my @foods = (\*(Aqchocolate\*(Aq, \*(Aqice cream\*(Aq, \*(Aqpeanut butter\*(Aq, \*(Aqpickles\*(Aq, \*(Aqpizza\*(Aq, \*(Aqbacon\*(Aq, \*(Aqpancakes\*(Aq, \*(Aqspaghetti\*(Aq, \*(Aqcookies\*(Aq); \& my @preferences = (\*(Aqloves\*(Aq, q|can\*(Aqt stand|, \*(Aqalways wants more\*(Aq, \*(Aqwill walk 100 miles for\*(Aq, \*(Aqonly eats\*(Aq, \*(Aqwould starve rather than eat\*(Aq); \& \& # run the parallel processes \& PERSONS: \& foreach my $person (qw(Fred Wilma Ernie Bert Lucy Ethel Curly Moe Larry)) { \& $pm\->start() and next PERSONS; \& \& # generate a random statement about food preferences \& my $statement = $person . \*(Aq \*(Aq . $preferences[int(rand @preferences)] . \*(Aq \*(Aq . $foods[int(rand @foods)]; \& \& # send it back to the parent process \& $pm\->finish(0, \e$statement); # note that it\*(Aqs a scalar REFERENCE, not the scalar itself \& } \& $pm\->wait_all_children; .Ve .PP A second datastructure retrieval example demonstrates how children decide whether or not to send anything back, what to send and how the parent should process whatever is retrieved. .PP .Vb 3 \& use Parallel::ForkManager 0.7.6; \& use Data::Dumper; # to display the data structures retrieved. \& use strict; \& \& my $pm = Parallel::ForkManager\->new(20); # using the system temp dir $L<File::Temp::tempdir() \& \& # data structure retrieval and handling \& my %retrieved_responses = (); # for collecting responses \& $pm \-> run_on_finish ( \& sub { \& my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_; \& \& # see what the child sent us, if anything \& if (defined($data_structure_reference)) { # test rather than assume child sent anything \& my $reftype = ref($data_structure_reference); \& print qq|ident "$ident" returned a "$reftype" reference.\en\en|; \& if (1) { # simple on/off switch to display the contents \& print &Dumper($data_structure_reference) . qq|end of "$ident" sent structure\en\en|; \& } \& \& # we can also collect retrieved data structures for processing after all children have exited \& $retrieved_responses{$ident} = $data_structure_reference; \& } else { \& print qq|ident "$ident" did not send anything.\en\en|; \& } \& } \& ); \& \& # generate a list of instructions \& my @instructions = ( # a unique identifier and what the child process should send \& {\*(Aqname\*(Aq => \*(Aq%ENV keys as a string\*(Aq, \*(Aqsend\*(Aq => \*(Aqkeys\*(Aq}, \& {\*(Aqname\*(Aq => \*(AqSend Nothing\*(Aq}, # not instructing the child to send anything back to the parent \& {\*(Aqname\*(Aq => \*(AqChilds %ENV\*(Aq, \*(Aqsend\*(Aq => \*(Aqall\*(Aq}, \& {\*(Aqname\*(Aq => \*(AqChild chooses randomly\*(Aq, \*(Aqsend\*(Aq => \*(Aqrandom\*(Aq}, \& {\*(Aqname\*(Aq => \*(AqInvalid send instructions\*(Aq, \*(Aqsend\*(Aq => \*(AqNa Na Nana Na\*(Aq}, \& {\*(Aqname\*(Aq => \*(AqENV values in an array\*(Aq, \*(Aqsend\*(Aq => \*(Aqvalues\*(Aq}, \& ); \& \& INSTRUCTS: \& foreach my $instruction (@instructions) { \& $pm\->start($instruction\->{\*(Aqname\*(Aq}) and next INSTRUCTS; # this time we are using an explicit, unique child process identifier \& \& # last step in child processing \& $pm\->finish(0) unless $instruction\->{\*(Aqsend\*(Aq}; # no data structure is sent unless this child is told what to send. \& \& if ($instruction\->{\*(Aqsend\*(Aq} eq \*(Aqkeys\*(Aq) { \& $pm\->finish(0, \ejoin(\*(Aq, \*(Aq, keys %ENV)); \& \& } elsif ($instruction\->{\*(Aqsend\*(Aq} eq \*(Aqvalues\*(Aq) { \& $pm\->finish(0, [values %ENV]); # kinda useless without knowing which keys they belong to... \& \& } elsif ($instruction\->{\*(Aqsend\*(Aq} eq \*(Aqall\*(Aq) { \& $pm\->finish(0, \e%ENV); # remember, we are not "returning" anything, just copying the hash to disc \& \& # demonstrate clearly that the child determines what type of reference to send \& } elsif ($instruction\->{\*(Aqsend\*(Aq} eq \*(Aqrandom\*(Aq) { \& my $string = q|I\*(Aqm just a string.|; \& my @array = qw(I am an array); \& my %hash = (type => \*(Aqassociative array\*(Aq, synonym => \*(Aqhash\*(Aq, cool => \*(Aqvery :)\*(Aq); \& my $return_choice = (\*(Aqstring\*(Aq, \*(Aqarray\*(Aq, \*(Aqhash\*(Aq)[int(rand 3)]; # randomly choose return data type \& $pm\->finish(0, \e$string) if ($return_choice eq \*(Aqstring\*(Aq); \& $pm\->finish(0, \e@array) if ($return_choice eq \*(Aqarray\*(Aq); \& $pm\->finish(0, \e%hash) if ($return_choice eq \*(Aqhash\*(Aq); \& \& # as a responsible child, inform parent that their instruction was invalid \& } else { \& $pm\->finish(0, \eqq|Invalid instructions: "$instruction\->{\*(Aqsend\*(Aq}".|); # ordinarily I wouldn\*(Aqt include invalid input in a response... \& } \& } \& $pm\->wait_all_children; # blocks until all forked processes have exited \& \& # post fork processing of returned data structures \& for (sort keys %retrieved_responses) { \& print qq|Post processing "$_"...\en|; \& } .Ve .SH "USING \fBRAND()\fP IN FORKED PROCESSES" .IX Header "USING RAND() IN FORKED PROCESSES" A caveat worth noting is that all forked processes will use the same random seed, so potentially providing the same results (see <http://blogs.perl.org/users/brian_phillips/2010/06/when\-rand\-isnt\-random.html>). If you are using \f(CW\*(C`rand()\*(C'\fR and want each forked child to use a different seed, you can add the following to your program: .PP .Vb 1 \& $pm\->run_on_start(sub { srand }); .Ve .SH "EXTENDING" .IX Header "EXTENDING" As of version 2.0.0, \f(CW\*(C`Parallel::ForkManager\*(C'\fR uses Moo under the hood. When a process is being forked from the parent object, the forked instance of the object will be modified to consume the Parallel::ForkManager::Child role. All of this makes extending Parallel::ForkManager to implement any storing/retrieving mechanism or any other behavior fairly easy. .SS "Example: store and retrieve data via a web service" .IX Subsection "Example: store and retrieve data via a web service" .Vb 2 \& { \& package Parallel::ForkManager::Web; \& \& use HTTP::Tiny; \& \& use Moo; \& extends \*(AqParallel::ForkManager\*(Aq; \& \& has ua => ( \& is => \*(Aqro\*(Aq, \& lazy => 1, \& default => sub { \& HTTP::Tiny\->new; \& } \& ); \& \& sub store { \& my( $self, $data ) = @_; \& \& $self\->ua\->post( "http://.../store/$$", { body => $data } ); \& } \& \& sub retrieve { \& my( $self, $kid_id ) = @_; \& \& $self\->ua\->get( "http://.../store/$kid_id" )\->{content}; \& } \& \& } \& \& my $fm = Parallel::ForkManager::Web\->new(2); \& \& $fm\->run_on_finish(sub{ \& my $retrieved = $_[5]; \& \& print "got ", $retrieved, "\en"; \& }); \& \& $fm\->start_child(sub { \& return $_**2; \& }) for 1..3; \& \& $fm\->wait_all_children; .Ve .SS "Example: have the child processes exit differently" .IX Subsection "Example: have the child processes exit differently" .Vb 1 \& use Parallel::ForkManager; \& \& package Parallel::ForkManager::Child::PosixExit { \& use Moo::Role; \& with \*(AqParallel::ForkManager::Child\*(Aq; \& \& sub finish { POSIX::_exit() }; \& } \& \& my $fm = Parallel::ForkManager\->new( \& max_proc => 1, \& child_role => \*(AqParallel::ForkManager::Child::PosixExit\*(Aq \& ); .Ve .SH "SECURITY" .IX Header "SECURITY" Parallel::ForkManager uses temporary files when a child process returns information to its parent process. The filenames are based on the process of the parent and child processes, so they are fairly easy to guess. So if security is a concern in your environment, make sure the directory used by Parallel::ForkManager is restricted to the current user only (the default behavior is to create a directory, via File::Temp's \f(CW\*(C`tempdir\*(C'\fR, which does that). .SH "TROUBLESHOOTING" .IX Header "TROUBLESHOOTING" .SS "PerlIO::gzip and Parallel::ForkManager do not play nice together" .IX Subsection "PerlIO::gzip and Parallel::ForkManager do not play nice together" If you are using PerlIO::gzip in your child processes, you may end up with garbled files. This is not really P::FM's fault, but rather a problem between PerlIO::gzip and \f(CW\*(C`fork()\*(C'\fR (see <https://rt.cpan.org/Public/Bug/Display.html?id=114557>). .PP Fortunately, it seems there is an easy way to fix the problem by adding the \*(L"unix\*(R" layer? I.e., .PP .Vb 1 \& open(IN, \*(Aq<:unix:gzip\*(Aq, ... .Ve .SH "BUGS AND LIMITATIONS" .IX Header "BUGS AND LIMITATIONS" Do not use Parallel::ForkManager in an environment where other child processes can affect the run of the main program; using this module is not recommended in an environment where \fBfork()\fR / \fBwait()\fR is already used. .PP If you want to use more than one copies of the Parallel::ForkManager, then you have to make sure that all children processes are terminated, before you use the second object in the main program. .PP You are free to use a new copy of Parallel::ForkManager in the child processes, although I don't think it makes sense. .SH "CREDITS" .IX Header "CREDITS" .Vb 6 \& Michael Gang (bug report) \& Noah Robin <sitz@onastick.net> (documentation tweaks) \& Chuck Hirstius <chirstius@megapathdsl.net> (callback exit status, example) \& Grant Hopwood <hopwoodg@valero.com> (win32 port) \& Mark Southern <mark_southern@merck.com> (bugfix) \& Ken Clarke <www.perlprogrammer.net> (datastructure retrieval) .Ve .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 dLux (Szabó, Balázs) <dlux@dlux.hu> .IP "\(bu" 4 Yanick Champoux <yanick@cpan.org> .IP "\(bu" 4 Gabor Szabo <gabor@szabgab.com> .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2024, 2015 by Balázs Szabó. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.