I was looking for a way to read the output of an external command piping its output to a script in a non-blocking way. I read that using Fcntl's fcntl() can be used to add the O_NONBLOCK flag to the file handle and wonder whether that is a safe practice when that filehandle came from opening an external command and reading its output using: open(my $fh, '-|', 'ls -al'); This is an example:
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); my $pid = open my $fh, '-|', 'sleep 3; echo aaaa' // die $!; my $flags = fcntl($fh, F_GETFL, 0) or die "failed to get flags, $!"; + fcntl($fh, F_SETFL, $flags | O_NONBLOCK) or die "Couldn't set file fla +gs: $!\n"; my $output = <$fh>; if( defined $output ){ print "got output: '$output'\n" } else { print "no output right now.\n" } print "now waiting to end ...\n"; #waitpid $pid, 0; close($fh); #kill 'TERM', $pid; print "end.\n";
I wanted to turn the above into a CUFP but I am not sure what are the caveats wrt Perl and OS. Anyone knows if any?
bw, bliako
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |