问题描述:

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?

网友答案:

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.

网友答案:

You don't give any hint about what $brcmd might be, but since you have opened a pipe from it I suggest that you read from that pipe and wait for end of file

Something like this, perhaps?

open my $br_fh, '-|', $brcmd or die "Cannot open BR command: $!";

my @output = <$br_fh>;
相关阅读:
Top