Reputation:
I have seen these two forms of pipe open
in perl.
One is simple pipe open
open FH,'| command';
and other is safe pipe open
open FH,'|-','command';
Now, What is the use of -
in second one? They both write to pipe. I know that -
forks new process.
Does simple |
also creates new process?
When will/should we use safe pipe open |-
?
Upvotes: 2
Views: 265
Reputation: 386501
There is no difference between
open my $PIPE, '| command';
vs
open my $PIPE, '|-', 'command';
The "safe" open is actually
open my $PIPE, '|-', 'program', @one_or_more_args;
This version is guaranteed to launch program directly; no shell is invoked. It also saves you from having to turn arguments into shell literals. In other words,
open my $FH, '|-', 'program', @one_or_more_args;
is similar to
use String::ShellQuote qw( shell_quote );
open my $FH, '|'.shell_quote('program', @one_or_more_args);
but without the shell (so less resources are wasted, you get the program's PID instead of a shell's, and you get to know if the program died from a signal).
Unfortunately, there's no syntax for a program with zero args like there is for system
.
(There's also open my $PIPE, "|-"
with no further args, but that's something else.)
Upvotes: 3
Reputation: 13792
You have to use the -
when you plan to(you want to) pipe from a fork of yourself (-|
) or to a fork of yourself |-
. The open
function returns the child's process ID in the parent process and 0 in the child process. Example:
if( open(TO, "|-") ) {
# Parent process
print TO $from_parent;
}
else {
# Child process
$to_child = <STDIN>;
exit;
}
Upvotes: 1