简体   繁体   中英

Difference between pipe open '|' and '|-' (safe pipe open)

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 |- ?

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.)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM