in reply to Leaking a file descriptor into a child to use with /proc/self/fd/3

We are trying to open a file descriptor and access it from a forked + exec child.

Here's a working SSCCE counterexample. It uses the PPID to retrieve the correct FD.

#!/usr/bin/env perl use strict; use warnings; use autodie; $| = 1; open my $in, '<', '/etc/passwd'; my $ppid = $$; unless (fork) { print "CHILD: "; exec ("grep", "root", "/proc/$ppid/fd/" . fileno($in)); } else { print "PARENT: still going\n"; wait; } close $in;

Here's the simpler one for not shelling out:

#!/usr/bin/env perl use strict; use warnings; use autodie; $| = 1; open my $in, '<', '/etc/passwd'; unless (fork) { print "CHILD: $_", for grep { /root/ } <$in>; print "CHILD: we're done here\n"; exit; } else { print "PARENT: still going\n"; wait; } close $in;

Replies are listed 'Best First'.
Re^2: Leaking a file descriptor into a child to use with /proc/self/fd/3
by ewheeler (Novice) on Feb 26, 2020 at 23:45 UTC

    Neat idea, we noticed that PPID still referenced it as well--however if the parent exits before the child uses the FD then it may not be consistent. $^F or fcntl for CLOEXEC is the solution here.