Talking to Yourself
Another approach to IPC is to make your program talk to itself, in a manner of speaking. Actually, your process talks over pipes to a forked copy of itself. It works much like the piped open we talked about in the last section, except that the child process continues executing your script instead of some other command.
To represent this to the open
function, you use a pseudocommand consisting of a minus. So the second
argument to open looks like either
“–|” or “|–”, depending on whether you want to pipe
from yourself or to yourself. As with an ordinary fork command, the open function returns the child’s process ID
in the parent process but 0 in the
child process. Another asymmetry is that the filehandle named by the
open is used only in the parent
process. The child’s end of the pipe is hooked to either STDIN or STDOUT as appropriate. That is, if you open a
pipe to minus with |–, you can write to the filehandle you
opened, and your kid will find this in STDIN:
if (open(TO, "|–")) {
print TO $fromparent;
}
else {
$tochild = <STDIN>;
exit;
}If you open a pipe from minus with –|, you can read from the filehandle you
opened, which will return whatever your kid writes to STDOUT:
if (open(FROM, "–|")) {
$toparent = <FROM>;
}
else {
print STDOUT $fromchild;
exit;
}One common application of this construct is to bypass the shell when you want to open a pipe from a command. You might want to do this because you don’t want the shell to interpret any possible metacharacters ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access