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

Hi there,

I know we can do it with backticks ($line =`grep $search file.info`) but i've to use the exec command.

What i'm doing is forking a process and then trying to pass the result of the exec (executed in the child process) to the parent process instead of the STDOUT.

$ReturnValue=fork; if ( $ReturnValue==0) { exec '/bin/date'; } elsif (defined $ReturnValue) { $pid = wait; # i need to get the value of date right here } else { die "Fork error: $!\n"; }
I know there is no point of passing the date value in such manners. This is just a simplified example of what i'm trying to do.

Cheers,

update (broquaint): added <code> tags

Replies are listed 'Best First'.
Re: Is there anyway to redirect the output of exec?
by Zaxo (Archbishop) on Jun 02, 2003 at 08:51 UTC

    exec transfers control to the system utility you call. The 'parent' is metamorphosed: it does not bear young. You can see that with:

    $ perl -e'print $$, $/; exec "perl", "-e", "print $$;"' 20540 20540$
    You can redirect output by opening *STDOUT to what you want before exec.

    After Compline,
    Zaxo

Re: Is there anyway to redirect the output of exec?
by edan (Curate) on Jun 02, 2003 at 08:37 UTC

    You'll want to use open to fork the child, as in:

    #!/usr/bin/perl use strict; use warnings; my $pid = open(CHILD, "-|"); if ($pid) { # parent print "parent got:\n"; print while(<CHILD>); close CHILD; # this waits on child } elsif ($pid == 0) { # child print "kid here!\n"; exec '/bin/date' or die "Can't exec date $!\n"; } else { die "fork error: $!\n"; }

    Hope that helps...

    --
    3dan
Re: Is there anyway to redirect the output of exec?
by arthas (Hermit) on Jun 02, 2003 at 08:54 UTC

    Maybe that was exactly what you desidered, anyhow beware that exec never returns, as it terminates the current program and executes the external command you pass as parameter. You should use system if you want to get control again after the execution of the command.

    Michele.