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

Greetings all, using the code found here, I constructed a program to search for a particular running process. Instead of getting the list, I get the ps USAGE message. why? Here is my code:
#!/usr/bin/perl -w use strict; my $process = "perl"; my @output; my $kidpid; if ($kidpid = open(PIPE, "-|")) { # Parent process. Read data from the child. @output = <PIPE>; } else { # Child process. Execute the command. die "could not fork" if !defined($kidpid); exec ("ps", "-ef", "|", "grep", $process) or die "exec failed: $!"; }
BTW, I am currently looking into Proc::ProcessTable... thanks, mike

Replies are listed 'Best First'.
Re: passing array arguments to exec()
by Kanji (Parson) on Apr 17, 2001 at 04:02 UTC

    You're explicitly telling exec that you want to bypass any parsing by the shell, but then trying to pipe the output of the command into another ... which is something that is usually handled by the shell, so you end up passing the pipe and the grep as arguments to ps which has no idea what to do with a |.

    Instead, you want to pass exec a single string like...

      exec("ps -ef | grep $process");

    ... so the shell handles the piping, or perform the grep yourself within perl using the like-named grep on the captured output.

    Also, you might want to look at the Shell module, which'd let you turn your code into (IMHO) the more legible ...

    #!/usr/bin/perl -w use strict; use Shell 'ps'; my $process = "perl"; my @output = grep /$process/ => ps("-ef");

        --k.


Re: passing array arguments to exec()
by Masem (Monsignor) on Apr 17, 2001 at 03:51 UTC
    I believe that the pipe symbol "|" is usually interpreted by the shell, and is not processed by exec(), thus, ps is seeing the "|", and other arguements too.

    Now, given that perl has a very nice built in grep, there's no reason to try to pipe in the eval. Simply, in your parent, after reading the pipe, do a line like..

    @output = grep { /$process/ } @output;
    to do the same thing.
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain