Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Fork / use Warnings Confusion

by bichonfrise74 (Vicar)
on May 13, 2010 at 22:10 UTC ( #839911=perlquestion: print w/replies, xml ) Need Help??

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 line 15. forking child. Can't exec "lst": No such file or directory at line 11.
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 (Archbishop) 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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://839911]
Approved by AnomalousMonk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2022-10-05 00:24 GMT
Find Nodes?
    Voting Booth?
    My preferred way to holiday/vacation is:

    Results (20 votes). Check out past polls.