How to pass a variable from a child process (fork by Parallel::ForkManager)?

I think you’re misunderstanding what a fork does. When you successfully fork, you’re creating a subprocess, independent from the process you started with, to continue doing work. Because it’s a separate process, it has its own memory, variables, etc., even though some of these started out as copies from the parent process.

So you’re setting $commandoutput[0] in each subprocess, but then, when that subprocess dies, so does the content of its copy of @commandoutput.

You can either run each command serially, or you can use threads (which comes with a host of other issues – your code would need some significant redesign to work even with threads), or you can use events (POE, AnyEvent, etc., and this will be another significant redesign). Or you could run each command with its output put into temporary files, then, once all the children are done, read each file and continue. This also comes with issues, but generally fewer issues than the others.

Leave a Comment