{
    "content": [
        {
            "type": "text",
            "text": "# Parallel::ForkManager (perldoc)\n\n## NAME\n\nParallel::ForkManager - A simple parallel processing fork manager\n\n## SYNOPSIS\n\nuse Parallel::ForkManager;\nmy $pm = Parallel::ForkManager->new($MAXPROCESSES);\nDATALOOP:\nforeach my $data (@alldata) {\n# Forks and returns the pid for the child:\nmy $pid = $pm->start and next DATALOOP;\n... do some work with $data in the child process ...\n$pm->finish; # Terminates the child process\n}\n\n## DESCRIPTION\n\nThis module is intended for use in operations that can be done in parallel where the number of\nprocesses to be forked off should be limited. Typical use is a downloader which will be\nretrieving hundreds/thousands of files.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **METHODS** (1 subsections)\n- **CALLBACKS**\n- **BLOCKING CALLS**\n- **EXAMPLES** (3 subsections)\n- **EXTENDING** (2 subsections)\n- **SECURITY**\n- **TROUBLESHOOTING** (1 subsections)\n- **BUGS AND LIMITATIONS** (1 subsections)\n- **CREDITS**\n- **AUTHORS**\n- **COPYRIGHT AND LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Parallel::ForkManager",
        "section": "",
        "mode": "perldoc",
        "summary": "Parallel::ForkManager - A simple parallel processing fork manager",
        "synopsis": "use Parallel::ForkManager;\nmy $pm = Parallel::ForkManager->new($MAXPROCESSES);\nDATALOOP:\nforeach my $data (@alldata) {\n# Forks and returns the pid for the child:\nmy $pid = $pm->start and next DATALOOP;\n... do some work with $data in the child process ...\n$pm->finish; # Terminates the child process\n}",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [
            "This small example can be used to get URLs in parallel.",
            "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 =~ /^.*\\/(.*?)$/;",
            "if (!$fn) {",
            "warn \"Cannot determine filename from $fn\\n\";",
            "} else {",
            "$0 .= \" \" . $fn;",
            "print \"Getting $fn from $link\\n\";",
            "my $rc = getstore($link, $fn);",
            "print \"$link downloaded. response code: $rc\\n\";",
            "};",
            "$pm->finish;",
            "};",
            "Example of a program using callbacks to get child exit codes:",
            "use strict;",
            "use Parallel::ForkManager;",
            "my $maxprocs = 5;",
            "my @names = qw( Fred Jim Lily Steve Jessica Bob Dave Christine Rico Sara );",
            "# hash to resolve PID's back to child specific information",
            "my $pm = Parallel::ForkManager->new($maxprocs);",
            "# Setup a callback for when a child finishes up so we can",
            "# get it's exit code",
            "$pm->runonfinish( sub {",
            "my ($pid, $exitcode, $ident) = @;",
            "print \" $ident just got out of the pool \".",
            "\"with PID $pid and exit code: $exitcode\\n\";",
            "});",
            "$pm->runonstart( sub {",
            "my ($pid, $ident)=@;",
            "print \" $ident started, pid: $pid\\n\";",
            "});",
            "$pm->runonwait( sub {",
            "print \" Have to wait for one children ...\\n\"",
            "},",
            "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\\n\";",
            "sleep ( 2 * $child );",
            "print \"$names[$child], Child $child is about to get out...\\n\";",
            "sleep 1;",
            "$pm->finish($child); # pass an exit code to finish",
            "print \"Waiting for Children...\\n\";",
            "$pm->waitallchildren;",
            "print \"Everybody is out of the pool!\\n\";",
            "In this simple example, each child sends back a string reference.",
            "use Parallel::ForkManager 0.7.6;",
            "use strict;",
            "my $pm = Parallel::ForkManager->new(2, '/server/path/to/temp/dir/');",
            "# data structure retrieval and handling",
            "$pm -> runonfinish ( # called BEFORE the first call to start()",
            "sub {",
            "my ($pid, $exitcode, $ident, $exitsignal, $coredump, $datastructurereference) = @;",
            "# retrieve data structure from child",
            "if (defined($datastructurereference)) {  # children are not forced to send anything",
            "my $string = ${$datastructurereference};  # child passed a string reference",
            "print \"$string\\n\";",
            "else {  # problems occurring during storage or retrieval will throw a warning",
            "print qq|No message received from child process $pid!\\n|;",
            ");",
            "# prep random statement components",
            "my @foods = ('chocolate', 'ice cream', 'peanut butter', 'pickles', 'pizza', 'bacon', 'pancakes', 'spaghetti', 'cookies');",
            "my @preferences = ('loves', q|can't stand|, 'always wants more', 'will walk 100 miles for', 'only eats', 'would starve rather than eat');",
            "# 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 . ' ' . $preferences[int(rand @preferences)] . ' ' . $foods[int(rand @foods)];",
            "# send it back to the parent process",
            "$pm->finish(0, \\$statement);  # note that it's a scalar REFERENCE, not the scalar itself",
            "$pm->waitallchildren;",
            "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.",
            "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 %retrievedresponses = ();  # for collecting responses",
            "$pm -> runonfinish (",
            "sub {",
            "my ($pid, $exitcode, $ident, $exitsignal, $coredump, $datastructurereference) = @;",
            "# see what the child sent us, if anything",
            "if (defined($datastructurereference)) {  # test rather than assume child sent anything",
            "my $reftype = ref($datastructurereference);",
            "print qq|ident \"$ident\" returned a \"$reftype\" reference.\\n\\n|;",
            "if (1) {  # simple on/off switch to display the contents",
            "print &Dumper($datastructurereference) . qq|end of \"$ident\" sent structure\\n\\n|;",
            "# we can also collect retrieved data structures for processing after all children have exited",
            "$retrievedresponses{$ident} = $datastructurereference;",
            "} else {",
            "print qq|ident \"$ident\" did not send anything.\\n\\n|;",
            ");",
            "# generate a list of instructions",
            "my @instructions = (  # a unique identifier and what the child process should send",
            "{'name' => '%ENV keys as a string', 'send' => 'keys'},",
            "{'name' => 'Send Nothing'},  # not instructing the child to send anything back to the parent",
            "{'name' => 'Childs %ENV', 'send' => 'all'},",
            "{'name' => 'Child chooses randomly', 'send' => 'random'},",
            "{'name' => 'Invalid send instructions', 'send' => 'Na Na Nana Na'},",
            "{'name' => 'ENV values in an array', 'send' => 'values'},",
            ");",
            "INSTRUCTS:",
            "foreach my $instruction (@instructions) {",
            "$pm->start($instruction->{'name'}) and next INSTRUCTS;  # this time we are using an explicit, unique child process identifier",
            "# last step in child processing",
            "$pm->finish(0) unless $instruction->{'send'};  # no data structure is sent unless this child is told what to send.",
            "if ($instruction->{'send'} eq 'keys') {",
            "$pm->finish(0, \\join(', ', keys %ENV));",
            "} elsif ($instruction->{'send'} eq 'values') {",
            "$pm->finish(0, [values %ENV]);  # kinda useless without knowing which keys they belong to...",
            "} elsif ($instruction->{'send'} eq 'all') {",
            "$pm->finish(0, \\%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->{'send'} eq 'random') {",
            "my $string = q|I'm just a string.|;",
            "my @array = qw(I am an array);",
            "my %hash = (type => 'associative array', synonym => 'hash', cool => 'very :)');",
            "my $returnchoice = ('string', 'array', 'hash')[int(rand 3)];  # randomly choose return data type",
            "$pm->finish(0, \\$string) if ($returnchoice eq 'string');",
            "$pm->finish(0, \\@array) if ($returnchoice eq 'array');",
            "$pm->finish(0, \\%hash) if ($returnchoice eq 'hash');",
            "# as a responsible child, inform parent that their instruction was invalid",
            "} else {",
            "$pm->finish(0, \\qq|Invalid instructions: \"$instruction->{'send'}\".|);  # ordinarily I wouldn't include invalid input in a response...",
            "$pm->waitallchildren;  # blocks until all forked processes have exited",
            "# post fork processing of returned data structures",
            "for (sort keys %retrievedresponses) {",
            "print qq|Post processing \"$\"...\\n|;",
            "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/brianphillips/2010/06/when-rand-isnt-random.html>). If you are",
            "using \"rand()\" and want each forked child to use a different seed, you can add the following to",
            "your program:",
            "$pm->runonstart(sub { srand });"
        ],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 14,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 48,
                "subsections": []
            },
            {
                "name": "METHODS",
                "lines": 78,
                "subsections": [
                    {
                        "name": "wait_for_available_procs",
                        "lines": 17
                    }
                ]
            },
            {
                "name": "CALLBACKS",
                "lines": 39,
                "subsections": []
            },
            {
                "name": "BLOCKING CALLS",
                "lines": 73,
                "subsections": []
            },
            {
                "name": "EXAMPLES",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Parallel get",
                        "lines": 22
                    },
                    {
                        "name": "Callbacks",
                        "lines": 46
                    },
                    {
                        "name": "Data structure retrieval",
                        "lines": 128
                    }
                ]
            },
            {
                "name": "EXTENDING",
                "lines": 5,
                "subsections": [
                    {
                        "name": "Example: store and retrieve data via a web service",
                        "lines": 44
                    },
                    {
                        "name": "Example: have the child processes exit differently",
                        "lines": 14
                    }
                ]
            },
            {
                "name": "SECURITY",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "TROUBLESHOOTING",
                "lines": 1,
                "subsections": [
                    {
                        "name": "PerlIO::gzip and Parallel::ForkManager do not play nice together",
                        "lines": 8
                    }
                ]
            },
            {
                "name": "BUGS AND LIMITATIONS",
                "lines": 2,
                "subsections": [
                    {
                        "name": "wait",
                        "lines": 7
                    }
                ]
            },
            {
                "name": "CREDITS",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENSE",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Parallel::ForkManager - A simple parallel processing fork manager\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 2.02\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use Parallel::ForkManager;\n\nmy $pm = Parallel::ForkManager->new($MAXPROCESSES);\n\nDATALOOP:\nforeach my $data (@alldata) {\n# Forks and returns the pid for the child:\nmy $pid = $pm->start and next DATALOOP;\n\n... do some work with $data in the child process ...\n\n$pm->finish; # Terminates the child process\n}\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This module is intended for use in operations that can be done in parallel where the number of\nprocesses to be forked off should be limited. Typical use is a downloader which will be\nretrieving hundreds/thousands of files.\n\nThe code for a downloader would look something like this:\n\nuse LWP::Simple;\nuse Parallel::ForkManager;\n\n...\n\nmy @links=(\n[\"http://www.foo.bar/rulez.data\",\"rulezdata.txt\"],\n[\"http://new.host/moredata.doc\",\"moredata.doc\"],\n...\n);\n\n...\n\n# Max 30 processes for parallel download\nmy $pm = Parallel::ForkManager->new(30);\n\nLINKS:\nforeach my $linkarray (@links) {\n$pm->start and next LINKS; # do the fork\n\nmy ($link, $fn) = @$linkarray;\nwarn \"Cannot get $fn from $link\"\nif getstore($link, $fn) != RCOK;\n\n$pm->finish; # do the exit in the child process\n}\n$pm->waitallchildren;\n\nFirst you need to instantiate the ForkManager with the \"new\" constructor. You must specify the\nmaximum number of processes to be created. If you specify 0, then NO fork will be done; this is\ngood for debugging purposes.\n\nNext, use $pm->start to do the fork. $pm returns 0 for the child process, and child pid for the\nparent process (see also \"fork()\" in perlfunc(1p)). The \"and next\" skips the internal loop in\nthe parent process. NOTE: $pm->start dies if the fork fails.\n\n$pm->finish terminates the child process (assuming a fork was done in the \"start\").\n\nNOTE: You cannot use $pm->start if you are already in the child process. If you want to manage\nanother set of subprocesses in the child process, you must instantiate another\nParallel::ForkManager object!\n",
                "subsections": []
            },
            "METHODS": {
                "content": "The comment letter indicates where the method should be run. P for parent, C for child.\n\nnew $processes\nInstantiate a new Parallel::ForkManager object. You must specify the maximum number of\nchildren to fork off. If you specify 0 (zero), then no children will be forked. This is\nintended for debugging purposes.\n\nThe optional second parameter, $tempdir, is only used if you want the children to send back\na reference to some data (see RETRIEVING DATASTRUCTURES below). If not provided, it is set\nvia a call to File::Temp::tempdir().\n\nThe new method will die if the temporary directory does not exist or it is not a directory.\n\nSince version 2.00, the constructor can also be called in the typical Moo/Moose fashion.\nI.e.\n\nmy $fm = Parallel::ForkManager->new(\nmaxprocs => 4,\ntempdir => '...',\nchildrole => 'Parallel::ForkManager::CustomChild',\n);\n\nchildrole\nReturns the name of the role consumed by the ForkManager object in child processes.\nDefaults to Parallel::ForkManager::Child and can be set to something else via the\nconstructor.\n\nstart [ $processidentifier ]\nThis method does the fork. It returns the pid of the child process for the parent, and 0\nfor the child process. If the $processes parameter for the constructor is 0 then, assuming\nyou're in the child process, $pm->start simply returns 0.\n\nAn optional $processidentifier can be provided to this method... It is used by the\n\"runonfinish\" callback (see CALLBACKS) for identifying the finished process.\n\nstartchild [ $processidentifier, ] \\&callback\nLike \"start\", but will run the &callback as the child. If the callback returns anything,\nit'll be passed as the data to transmit back to the parent process via \"finish()\".\n\nfinish [ $exitcode [, $datastructurereference] ]\nCloses the child process by exiting and accepts an optional exit code (default exit code is\n0) which can be retrieved in the parent via callback. If the second optional parameter is\nprovided, the child attempts to send its contents back to the parent. If you use the\nprogram in debug mode ($processes == 0), this method just calls the callback.\n\nIf the $datastructurereference is provided, then it is serialized and passed to the\nparent process. See RETRIEVING DATASTRUCTURES for more info.\n\nsetmaxprocs $processes\nAllows you to set a new maximum number of children to maintain.\n\nwaitallchildren\nYou can call this method to wait for all the processes which have been forked. This is a\nblocking wait.\n\nreapfinishedchildren\nThis is a non-blocking call to reap children and execute callbacks independent of calls to\n\"start\" or \"waitallchildren\". Use this in scenarios where \"start\" is called infrequently\nbut you would like the callbacks executed quickly.\n\nisparent\nReturns \"true\" if within the parent or \"false\" if within the child.\n\nischild\nReturns \"true\" if within the child or \"false\" if within the parent.\n\nmaxprocs\nReturns the maximal number of processes the object will fork.\n\nrunningprocs\nReturns the pids of the forked processes currently monitored by the\n\"Parallel::ForkManager\". Note that children are still reported as running until the fork\nmanager harvest them, via the next call to \"start\" or \"waitallchildren\".\n\nmy @pids = $pm->runningprocs;\n\nmy $nbrchildren =- $pm->runningprocs;\n",
                "subsections": [
                    {
                        "name": "wait_for_available_procs",
                        "content": "Wait until $n available process slots are available. If $n is not given, defaults to *1*.\n\nwaitpidblockingsleep\nReturns the sleep period, in seconds, of the pseudo-blocking calls. The sleep period can be\na fraction of second.\n\nReturns 0 if disabled.\n\nDefaults to 1 second.\n\nSee *BLOCKING CALLS* for more details.\n\nsetwaitpidblockingsleep $seconds\nSets the the sleep period, in seconds, of the pseudo-blocking calls. Set to 0 to disable.\n\nSee *BLOCKING CALLS* for more details.\n"
                    }
                ]
            },
            "CALLBACKS": {
                "content": "You can define callbacks in the code, which are called on events like starting a process or upon\nfinish. Declare these before the first call to start().\n\nThe callbacks can be defined with the following methods:\n\nrunonfinish $code [, $pid ]\nYou can define a subroutine which is called when a child is terminated. It is called in the\nparent process.\n\nThe parameters of the $code are the following:\n\n- pid of the process, which is terminated\n- exit code of the program\n- identification of the process (if provided in the \"start\" method)\n- exit signal (0-127: signal name)\n- core dump (1 if there was core dump at exit)\n- datastructure reference or undef (see RETRIEVING DATASTRUCTURES)\n\nrunonstart $code\nYou can define a subroutine which is called when a child is started. It called after the\nsuccessful startup of a child in the parent process.\n\nThe parameters of the $code are the following:\n\n- pid of the process which has been started\n- identification of the process (if provided in the \"start\" method)\n\nrunonwait $code, [$period]\nYou can define a subroutine which is called when the child process needs to wait for the\nstartup. If $period is not defined, then one call is done per child. If $period is defined,\nthen $code is called periodically and the module waits for $period seconds between the two\ncalls. Note, $period can be fractional number also. The exact \"$period seconds\" is not\nguaranteed, signals can shorten and the process scheduler can make it longer (on busy\nsystems).\n\nThe $code called in the \"start\" and the \"waitallchildren\" method also.\n\nNo parameters are passed to the $code on the call.\n",
                "subsections": []
            },
            "BLOCKING CALLS": {
                "content": "When it comes to waiting for child processes to terminate, \"Parallel::ForkManager\" is between a\nfork and a hard place (if you excuse the terrible pun). The underlying Perl \"waitpid\" function\nthat the module relies on can block until either one specific or any child process terminate,\nbut not for a process part of a given group.\n\nThis means that the module can do one of two things when it waits for one of its child processes\nto terminate:\n\nOnly wait for its own child processes\nThis is done via a loop using a \"waitpid\" non-blocking call and a sleep statement. The code\ndoes something along the lines of\n\nwhile(1) {\nif ( any of the P::FM child process terminated ) {\nreturn its pid\n}\n\nsleep $sleepperiod\n}\n\nThis is the default behavior that the module will use. This is not the most efficient way to\nwait for child processes, but it's the safest way to ensure that \"Parallel::ForkManager\"\nwon't interfere with any other part of the codebase.\n\nThe sleep period is set via the method \"setwaitpidblockingsleep\".\n\nBlock until any process terminate\nAlternatively, \"Parallel::ForkManager\" can call \"waitpid\" such that it will block until any\nchild process terminate. If the child process was not one of the monitored subprocesses, the\nwait will resume. This is more efficient, but mean that \"P::FM\" can captures (and discards)\nthe termination notification that a different part of the code might be waiting for.\n\nIf this is a race condition that doesn't apply to your codebase, you can set the\n*waitpidblockingsleep* period to 0, which will enable \"waitpid\" call blocking.\n\nmy $pm = Parallel::ForkManager->new( 4 );\n\n$pm->setwaitpidblockingsleep(0);  # true blocking calls enabled\n\nfor ( 1..100 ) {\n$pm->start and next;\n\n...; # do work\n\n$pm->finish;\n}\n\nRETRIEVING DATASTRUCTURES from child processes\nThe ability for the parent to retrieve data structures is new as of version 0.7.6.\n\nEach child process may optionally send 1 data structure back to the parent. By data structure,\nwe mean a reference to a string, hash or array. The contents of the data structure are written\nout to temporary files on disc using the Storable modules' store() method. The reference is then\nretrieved from within the code you send to the runonfinish callback.\n\nThe data structure can be any scalar perl data structure which makes sense: string, numeric\nvalue or a reference to an array, hash or object.\n\nThere are 2 steps involved in retrieving data structures:\n\n1) A reference to the data structure the child wishes to send back to the parent is provided as\nthe second argument to the finish() call. It is up to the child to decide whether or not to send\nanything back to the parent.\n\n2) The data structure reference is retrieved using the callback provided in the runonfinish()\nmethod.\n\nKeep in mind that data structure retrieval is not the same as returning a data structure from a\nmethod call. That is not what actually occurs. The data structure referenced in a given child\nprocess is serialized and written out to a file by Storable. The file is subsequently read back\ninto memory and a new data structure belonging to the parent process is created. Please consider\nthe performance penalty it can imply, so try to keep the returned structure small.\n",
                "subsections": []
            },
            "EXAMPLES": {
                "content": "",
                "subsections": [
                    {
                        "name": "Parallel get",
                        "content": "This small example can be used to get URLs in parallel.\n\nuse Parallel::ForkManager;\nuse LWP::Simple;\n\nmy $pm = Parallel::ForkManager->new(10);\n\nLINKS:\nfor my $link (@ARGV) {\n$pm->start and next LINKS;\nmy ($fn) = $link =~ /^.*\\/(.*?)$/;\nif (!$fn) {\nwarn \"Cannot determine filename from $fn\\n\";\n} else {\n$0 .= \" \" . $fn;\nprint \"Getting $fn from $link\\n\";\nmy $rc = getstore($link, $fn);\nprint \"$link downloaded. response code: $rc\\n\";\n};\n$pm->finish;\n};\n"
                    },
                    {
                        "name": "Callbacks",
                        "content": "Example of a program using callbacks to get child exit codes:\n\nuse strict;\nuse Parallel::ForkManager;\n\nmy $maxprocs = 5;\nmy @names = qw( Fred Jim Lily Steve Jessica Bob Dave Christine Rico Sara );\n# hash to resolve PID's back to child specific information\n\nmy $pm = Parallel::ForkManager->new($maxprocs);\n\n# Setup a callback for when a child finishes up so we can\n# get it's exit code\n$pm->runonfinish( sub {\nmy ($pid, $exitcode, $ident) = @;\nprint \" $ident just got out of the pool \".\n\"with PID $pid and exit code: $exitcode\\n\";\n});\n\n$pm->runonstart( sub {\nmy ($pid, $ident)=@;\nprint \" $ident started, pid: $pid\\n\";\n});\n\n$pm->runonwait( sub {\nprint \" Have to wait for one children ...\\n\"\n},\n0.5\n);\n\nNAMES:\nforeach my $child ( 0 .. $#names ) {\nmy $pid = $pm->start($names[$child]) and next NAMES;\n\n# This code is the child process\nprint \"This is $names[$child], Child number $child\\n\";\nsleep ( 2 * $child );\nprint \"$names[$child], Child $child is about to get out...\\n\";\nsleep 1;\n$pm->finish($child); # pass an exit code to finish\n}\n\nprint \"Waiting for Children...\\n\";\n$pm->waitallchildren;\nprint \"Everybody is out of the pool!\\n\";\n"
                    },
                    {
                        "name": "Data structure retrieval",
                        "content": "In this simple example, each child sends back a string reference.\n\nuse Parallel::ForkManager 0.7.6;\nuse strict;\n\nmy $pm = Parallel::ForkManager->new(2, '/server/path/to/temp/dir/');\n\n# data structure retrieval and handling\n$pm -> runonfinish ( # called BEFORE the first call to start()\nsub {\nmy ($pid, $exitcode, $ident, $exitsignal, $coredump, $datastructurereference) = @;\n\n# retrieve data structure from child\nif (defined($datastructurereference)) {  # children are not forced to send anything\nmy $string = ${$datastructurereference};  # child passed a string reference\nprint \"$string\\n\";\n}\nelse {  # problems occurring during storage or retrieval will throw a warning\nprint qq|No message received from child process $pid!\\n|;\n}\n}\n);\n\n# prep random statement components\nmy @foods = ('chocolate', 'ice cream', 'peanut butter', 'pickles', 'pizza', 'bacon', 'pancakes', 'spaghetti', 'cookies');\nmy @preferences = ('loves', q|can't stand|, 'always wants more', 'will walk 100 miles for', 'only eats', 'would starve rather than eat');\n\n# run the parallel processes\nPERSONS:\nforeach my $person (qw(Fred Wilma Ernie Bert Lucy Ethel Curly Moe Larry)) {\n$pm->start() and next PERSONS;\n\n# generate a random statement about food preferences\nmy $statement = $person . ' ' . $preferences[int(rand @preferences)] . ' ' . $foods[int(rand @foods)];\n\n# send it back to the parent process\n$pm->finish(0, \\$statement);  # note that it's a scalar REFERENCE, not the scalar itself\n}\n$pm->waitallchildren;\n\nA second datastructure retrieval example demonstrates how children decide whether or not to send\nanything back, what to send and how the parent should process whatever is retrieved.\n\nuse Parallel::ForkManager 0.7.6;\nuse Data::Dumper;  # to display the data structures retrieved.\nuse strict;\n\nmy $pm = Parallel::ForkManager->new(20);  # using the system temp dir $L<File::Temp::tempdir()\n\n# data structure retrieval and handling\nmy %retrievedresponses = ();  # for collecting responses\n$pm -> runonfinish (\nsub {\nmy ($pid, $exitcode, $ident, $exitsignal, $coredump, $datastructurereference) = @;\n\n# see what the child sent us, if anything\nif (defined($datastructurereference)) {  # test rather than assume child sent anything\nmy $reftype = ref($datastructurereference);\nprint qq|ident \"$ident\" returned a \"$reftype\" reference.\\n\\n|;\nif (1) {  # simple on/off switch to display the contents\nprint &Dumper($datastructurereference) . qq|end of \"$ident\" sent structure\\n\\n|;\n}\n\n# we can also collect retrieved data structures for processing after all children have exited\n$retrievedresponses{$ident} = $datastructurereference;\n} else {\nprint qq|ident \"$ident\" did not send anything.\\n\\n|;\n}\n}\n);\n\n# generate a list of instructions\nmy @instructions = (  # a unique identifier and what the child process should send\n{'name' => '%ENV keys as a string', 'send' => 'keys'},\n{'name' => 'Send Nothing'},  # not instructing the child to send anything back to the parent\n{'name' => 'Childs %ENV', 'send' => 'all'},\n{'name' => 'Child chooses randomly', 'send' => 'random'},\n{'name' => 'Invalid send instructions', 'send' => 'Na Na Nana Na'},\n{'name' => 'ENV values in an array', 'send' => 'values'},\n);\n\nINSTRUCTS:\nforeach my $instruction (@instructions) {\n$pm->start($instruction->{'name'}) and next INSTRUCTS;  # this time we are using an explicit, unique child process identifier\n\n# last step in child processing\n$pm->finish(0) unless $instruction->{'send'};  # no data structure is sent unless this child is told what to send.\n\nif ($instruction->{'send'} eq 'keys') {\n$pm->finish(0, \\join(', ', keys %ENV));\n\n} elsif ($instruction->{'send'} eq 'values') {\n$pm->finish(0, [values %ENV]);  # kinda useless without knowing which keys they belong to...\n\n} elsif ($instruction->{'send'} eq 'all') {\n$pm->finish(0, \\%ENV);  # remember, we are not \"returning\" anything, just copying the hash to disc\n\n# demonstrate clearly that the child determines what type of reference to send\n} elsif ($instruction->{'send'} eq 'random') {\nmy $string = q|I'm just a string.|;\nmy @array = qw(I am an array);\nmy %hash = (type => 'associative array', synonym => 'hash', cool => 'very :)');\nmy $returnchoice = ('string', 'array', 'hash')[int(rand 3)];  # randomly choose return data type\n$pm->finish(0, \\$string) if ($returnchoice eq 'string');\n$pm->finish(0, \\@array) if ($returnchoice eq 'array');\n$pm->finish(0, \\%hash) if ($returnchoice eq 'hash');\n\n# as a responsible child, inform parent that their instruction was invalid\n} else {\n$pm->finish(0, \\qq|Invalid instructions: \"$instruction->{'send'}\".|);  # ordinarily I wouldn't include invalid input in a response...\n}\n}\n$pm->waitallchildren;  # blocks until all forked processes have exited\n\n# post fork processing of returned data structures\nfor (sort keys %retrievedresponses) {\nprint qq|Post processing \"$\"...\\n|;\n}\n\nUSING RAND() IN FORKED PROCESSES\nA caveat worth noting is that all forked processes will use the same random seed, so potentially\nproviding the same results (see\n<http://blogs.perl.org/users/brianphillips/2010/06/when-rand-isnt-random.html>). If you are\nusing \"rand()\" and want each forked child to use a different seed, you can add the following to\nyour program:\n\n$pm->runonstart(sub { srand });\n"
                    }
                ]
            },
            "EXTENDING": {
                "content": "As of version 2.0.0, \"Parallel::ForkManager\" uses Moo under the hood. When a process is being\nforked from the parent object, the forked instance of the object will be modified to consume the\nParallel::ForkManager::Child role. All of this makes extending Parallel::ForkManager to\nimplement any storing/retrieving mechanism or any other behavior fairly easy.\n",
                "subsections": [
                    {
                        "name": "Example: store and retrieve data via a web service",
                        "content": "{\npackage Parallel::ForkManager::Web;\n\nuse HTTP::Tiny;\n\nuse Moo;\nextends 'Parallel::ForkManager';\n\nhas ua => (\nis => 'ro',\nlazy => 1,\ndefault => sub {\nHTTP::Tiny->new;\n}\n);\n\nsub store {\nmy( $self, $data ) = @;\n\n$self->ua->post( \"http://.../store/$$\", { body => $data } );\n}\n\nsub retrieve {\nmy( $self, $kidid ) = @;\n\n$self->ua->get( \"http://.../store/$kidid\" )->{content};\n}\n\n}\n\nmy $fm = Parallel::ForkManager::Web->new(2);\n\n$fm->runonfinish(sub{\nmy $retrieved = $[5];\n\nprint \"got \", $retrieved, \"\\n\";\n});\n\n$fm->startchild(sub {\nreturn $2;\n}) for 1..3;\n\n$fm->waitallchildren;\n"
                    },
                    {
                        "name": "Example: have the child processes exit differently",
                        "content": "use Parallel::ForkManager;\n\npackage Parallel::ForkManager::Child::PosixExit {\nuse Moo::Role;\nwith 'Parallel::ForkManager::Child';\n\nsub finish  { POSIX::exit() };\n}\n\nmy $fm = Parallel::ForkManager->new(\nmaxproc   => 1,\nchildrole => 'Parallel::ForkManager::Child::PosixExit'\n);\n"
                    }
                ]
            },
            "SECURITY": {
                "content": "Parallel::ForkManager uses temporary files when a child process returns information to its\nparent process. The filenames are based on the process of the parent and child processes, so\nthey are fairly easy to guess. So if security is a concern in your environment, make sure the\ndirectory used by Parallel::ForkManager is restricted to the current user only (the default\nbehavior is to create a directory, via File::Temp's \"tempdir\", which does that).\n",
                "subsections": []
            },
            "TROUBLESHOOTING": {
                "content": "",
                "subsections": [
                    {
                        "name": "PerlIO::gzip and Parallel::ForkManager do not play nice together",
                        "content": "If you are using PerlIO::gzip in your child processes, you may end up with garbled files. This\nis not really P::FM's fault, but rather a problem between PerlIO::gzip and \"fork()\" (see\n<https://rt.cpan.org/Public/Bug/Display.html?id=114557>).\n\nFortunately, it seems there is an easy way to fix the problem by adding the \"unix\" layer? I.e.,\n\nopen(IN, '<:unix:gzip', ...\n"
                    }
                ]
            },
            "BUGS AND LIMITATIONS": {
                "content": "Do not use Parallel::ForkManager in an environment where other child processes can affect the\nrun of the main program; using this module is not recommended in an environment where fork() /",
                "subsections": [
                    {
                        "name": "wait",
                        "content": "If you want to use more than one copies of the Parallel::ForkManager, then you have to make sure\nthat all children processes are terminated, before you use the second object in the main\nprogram.\n\nYou are free to use a new copy of Parallel::ForkManager in the child processes, although I don't\nthink it makes sense.\n"
                    }
                ]
            },
            "CREDITS": {
                "content": "Michael Gang (bug report)\nNoah Robin <sitz@onastick.net> (documentation tweaks)\nChuck Hirstius <chirstius@megapathdsl.net> (callback exit status, example)\nGrant Hopwood <hopwoodg@valero.com> (win32 port)\nMark Southern <marksouthern@merck.com> (bugfix)\nKen Clarke <www.perlprogrammer.net>  (datastructure retrieval)\n",
                "subsections": []
            },
            "AUTHORS": {
                "content": "*   dLux (Szabó, Balázs) <dlux@dlux.hu>\n\n*   Yanick Champoux <yanick@cpan.org>\n\n*   Gabor Szabo <gabor@szabgab.com>\n",
                "subsections": []
            },
            "COPYRIGHT AND LICENSE": {
                "content": "This software is copyright (c) 2018, 2016, 2015 by Balázs Szabó.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
                "subsections": []
            }
        }
    }
}