ealeon ealeon - 4 months ago 8
Perl Question

perl: execute a command via open and see if the command has finished

sub do_something {
while(1) {
#see if $brcmd has finished here
# if ($BR finished) ?
sleep 1;


}
}

open $BR, q{-|}, $brcmd
or die 'Cannot open BR';

do_something();

my $err = !(close $BR)


in the above code, i am open
$brcmd
which does something long
inside
do_something()
, I want to be able to check if
$brcmd
has finished

any suggestions?

Answer

it's just something that does for a long time (i used to read stuff from it but no longer need to). I just want to be able to know if it is finished.

i need to do completely something else while that is running but when that's finished i need to exit out. so i need to able to poll if it's done without capturing any out from it.

If those are your requirements, you should save the pid of the child (the return value of open), and then, when the parent is done, waitpid on the child.

perldoc -f open actually has an example of this:

my $child_pid = open(my $from_kid, "-|") // die "Can't fork: $!";

# ...

if ($child_pid) {
    # am the parent:
    # either write $to_kid or else read $from_kid
    ...
   waitpid $child_pid, 0;
} else {
    # am the child; use STDIN/STDOUT normally
    ...
    exit;
}

Of course, if you really do not need to read anything from the external command, you can fork then execute the external command using exec.

Comments