LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to redirect the output of exec command output in perl? (http://www.linuxquestions.org/questions/linux-newbie-8/how-to-redirect-the-output-of-exec-command-output-in-perl-631188/)

sudhap85 03-28-2008 02:11 AM

How to redirect the output of exec command output in perl?
 
In my code i want to redirect the o/p of exec to one file is it possible?


else {

if ($pid = fork) {

}

elsif (defined $pid) {

chdir $chdir if $chdir;

eval $extra if $extra;

exec $cmd or die "Unable to exec $cmd: $!\n";

} else {

die "Unable to fork: $!\n";

}

}


here $cmd am passing one processor cmd line args.so i want to preserve the o/p of that processor in to one file.

Can anyone help me?


sudha

theNbomr 03-28-2008 09:29 AM

This small example should explain:
Code:

#! /bin/perl -w
use strict;

    # open a command with command's output piped back to us
    #
    open( DIR, "ls|" ) || die "No ls";
    while( <DIR> ){      # read command's output from the pipe
        print $_;        # do something with what we read back from the proces
    }
    close DIR;        # be done
    exit;

You can use the same technique to pipe standard input into the command (but not both input & output).
No explicit fork() necessary. See also, readpipe.

--- rod.

prad77 03-28-2008 04:35 PM

The output of a command is directed to STDOUT. we can redirect this to a file for our use.

To read both a command's STDOUT and its STDERR separately, it's easiest and
safest to redirect them separately to files, and then read from those files
when the program is done: system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");

Gentoo

guivho 08-28-2009 03:35 PM

This is probably far too late to be helpful, but I bumped into this thread just now. You could add the desired redirection to your 'exec' command, e.g.:

exec "$cmd 1>stdout.text 2>stderr.txt" or die "Unable to exec $cmd: $!\n";

Hope this helps,

guivho


All times are GMT -5. The time now is 01:51 PM.