简体   繁体   中英

Closing stdin stdout and stderr the ptunnel way

I was intrigued by the way ptunnel closes stdin, stdout and stderr:

if (daemonize)
{
    ...
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
}

Is this a good way to close them? I am confused because freopen will open a file descriptor, which is not closed in that case.

No. It's not entirely safe.

It assumes the freopen() reuses the same file descriptors which is not guaranteed. So if freopen() uses a different file descriptor, say for example, for stdout other than 1 then your subsequent write() 's using that file descriptor will not work as expected. Because POSIX read/write functions use *_FILENO defined as:

/* Standard file descriptors.  */
#define STDIN_FILENO    0       /* Standard input.  */
#define STDOUT_FILENO   1       /* Standard output.  */
#define STDERR_FILENO   2       /* Standard error output.  */

for respective IO operations.

Instead you could do:

#include<unistd.h>

  fd = open("/dev/null",O_RDWR);
  dup2(fd,0);
  dup2(fd,1);
  dup2(fd,2); 

to achieve the same. Obvious downside is that open() and dup2() are POSIX functions and are not part of the C standard.

But you are safe as long as freopen() reuses the file descriptors 0, 1 & 2 respectively or you don't do any IO with that potentially incorrect file descriptor(s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM