c - Closing stdin stdout and stderr the ptunnel way -


i intrigued way ptunnel closes stdin, stdout , stderr:

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

is way close them? confused because freopen open file descriptor, not closed in case.

no. it's not entirely safe.

it assumes freopen() reuses same file descriptors not guaranteed. if freopen() uses different file descriptor, example, stdout other 1 subsequent write()'s using file descriptor not work 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 do:

#include<unistd.h>    fd = open("/dev/null",o_rdwr);   dup2(fd,0);   dup2(fd,1);   dup2(fd,2);  

to achieve same. obvious downside open() , dup2() posix functions , not part of c standard.

but safe long freopen() reuses file descriptors 0, 1 & 2 respectively or don't io potentially incorrect file descriptor(s).


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -