Passing Filehandles
Whenever you create a child process using fork, that new process inherits all its
parent’s open filehandles. Using filehandles for interprocess
communication is easiest to illustrate by using plain files first.
Understanding how this works is essential for mastering the fancier
mechanisms of pipes and sockets described later in this chapter.
The simplest example opens a file and starts up a child process. The child then uses the filehandle already opened for it:
open(INPUT, "< /etc/motd") || die "/etc/motd: $!";
if ($pid = fork) { waitpid($pid,0) }
else {
defined($pid) || die "fork: $!";
while (<INPUT>) { print "$.: $_" }
exit; # don't let child fall back into main code
}
# INPUT handle now at EOF in parentOnce access to a file has been granted by open, it stays granted until the filehandle is
closed; changes to the file’s permissions or to the owner’s access
privileges have no effect on accessibility. Even if the process later
alters its user or group IDs, or the file has its ownership changed to a
different user or group, that doesn’t affect filehandles that are
already open. Programs running under increased permissions (like set-id
programs or systems daemons) often open a file under their increased
rights and then hand off the filehandle to a child process that could
not have opened the file on its own.
Although this feature is of great convenience when used intentionally, it can also create security issues if filehandles accidentally leak from one program to ...
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