Kaz Kylheku <
157-07...@kylheku.com>:
>On 2018-06-05, Helmut Waitzmann <
nn.th...@xoxy.net> wrote:
>> To free the finally unused file descriptor #3 for the "cmd" and
>> "editprogram" processes (file descriptor hygiene), one could add
>> "3>&-" to each of them:
>>
>> $ (cmd 2>&1 1>&3 3>&- | editprogram 1>&2 3>&-) 3>&1 | filterprogram
>
>Why? Aren't these in a subshell that will terminate, thereby closing
>all its file descriptors?
Yes, the subshell running inside of the parentheses will terminate
as soon as "editprogram" terminates. But that wouldn't
necessarily close the opened file in the system's opened files
table, which the file descriptor #3 of the process running
"editprogram" is associated to.
For example, if "editprogram" forks a child, then terminates
itself, the child will keep write access to the pipe to
"filterprogram".
>If anything, wouldn't it be the outer shell, that needs to close the 3
>that it temporarily used in order to hand the subshell a duplicate of
>stdout?
The file descriptor #3 of the file descriptor table of the
subshell of the left hand side of the pipe to "filterprogram",
which is a duplicate of #1, won't survive the shell command line,
because file descriptors, which are opened/duplicated/closed as
part of a command invocation (other than the "exec" special shell
built-in command, when invoked without a program to exec), won't
survive that command invocation.
The problem is with the programs "cmd" and "editprogram", though:
In their file descriptor tables, each of them will have an opened
file descriptor #3, which they even don't know of. In the best
case, this is at least a waste of one file descriptor slot.
Also, with "editprogram", that might be a security issue, if
"editprogram" is supplied by some other party than the issuer of
the shell command line: "editprogram" should not be able to write
into the pipe to "filterprogram". Now, if "editprogram" were a
malign program, it could scan its file descriptor table by trying
to write to any of them, thus corrupting the data that
"filterprogram" is supposed to read.