ccan icon indicating copy to clipboard operation
ccan copied to clipboard

reopen STDIN and STDOUT as dev/null

Open Maxime2 opened this issue 9 years ago • 6 comments

It is better to reopen STDIN and STDOUT as well as they may be used in a third-party application using ccan.

Maxime2 avatar Jul 30 '15 02:07 Maxime2

But STDIN is read only while STDOUT and STDERR are write only.

Maxime2 avatar Jul 31 '15 01:07 Maxime2

Good point! A couple of typos to fix is all it needs then!

rustyrussell avatar Aug 02 '15 21:08 rustyrussell

Nope. If the new fd is already open, dup2() would close it before reusing. If the old fd is equal to the new fd dup2() does nothing. So there is no point to close fd if it is below or equal to STDERR_FILENO.

Maxime2 avatar Aug 03 '15 03:08 Maxime2

Maxim Zakharov [email protected] writes:

Nope. If the new fd is already open, dup2() would close it before reusing. If the old fd is equal to the new fd dup2() does nothing. So there is no point to close fd if it is below or equal to STDERR_FILENO.

Well, if you're assuming the continuity of stdin, stdout, and stderr, then how about this:

    if (open("/dev/null", O_RDONLY) != STDIN_FILENO)
            return false;
    /* Save some kernel memory by dup() for stdout & stderr */
    if (dup(open("/dev/null", O_WRONLY)) != STDERR_FILENO)
            return false;

Cheers, Rusty.

rustyrussell avatar Aug 03 '15 03:08 rustyrussell

It looks very good, but perhaps we need to add a comment that this code is rely on unix's property to always use lowest unused file descriptor. As I remember, Windows do not state such guaranty.

Maxime2 avatar Aug 03 '15 08:08 Maxime2

Maxim Zakharov [email protected] writes:

It looks very good, but perhaps we need to add a comment that this code is rely on unix's property to always use lowest unused file descriptor. As I remember, Windows do not state such guaranty.

Hmm, does this code even work on Windows at all? If so, might be nice to do it the long way, but it'll need a comment explaining the reason for the > test instead of == :)

Thanks, Rusty.

rustyrussell avatar Aug 04 '15 07:08 rustyrussell