http://qs321.pair.com?node_id=839911

bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

Below is my code.
#!/usr/bin/perl use strict; use warnings FATAL => 'all'; my $pid = fork(); my $output; if ($pid) { print "forking child.\n"; $output = qx( lst 2>&1 ); } waitpid ($pid, 0); print $output; __OUTPUT__ Use of uninitialized value in print at 2.pl line 15. forking child. Can't exec "lst": No such file or directory at 2.pl line 11.
Questions:
1. Why am I getting the uninitialized value message? Line 15 is the print $output.
2. Why is the error showing up first? Shouldn't it "wait" until the child is finished before attempting to print the output?
3. If I remove 'use warnings...', then I will not see the uninitialized message. But print $output will not show me anything.

Replies are listed 'Best First'.
Re: Fork / use Warnings Confusion
by JavaFan (Canon) on May 13, 2010 at 22:28 UTC
    1. You have two processes trying to attempt the print: both the parent and the child. But you are setting $output in only one of them. And in the other, since "lst" fails, $output is set to undef.
    2. The parent will wait. The child, which doesn't have a child process $pid, will not.
    3. It won't show you anything because printing undef prints the empty string. Even with two empty strings, there's still nothing to see.
Re: Fork / use Warnings Confusion
by choroba (Cardinal) on May 13, 2010 at 22:33 UTC
    Your shell cannot run the lst command. Therefore, you get the error Can't exec.... The $output variable is empty, that's why you get the warning and no output. The documentation of fork says you cannot share a variable between the parent and child process.