APUE (Figure 13.1) says for creating a daemon, after closing all open file descriptors, attach the descriptors 0,1,2 to /dev/null as follows:
/*
* Close all open file descriptors.
*/
if (rl.rlim_max == RLIM_INFINITY)
rl.rlim_max = 1024;
for (i = 0; i < rl.rlim_max; i++)
close(i);
/*
* Attach file descriptors 0, 1, and 2 to /dev/null.
*/
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
My question is: Is it necessary to attach file descriptors 0, 1, 2 or can they all remain unattached?
You will get errors if anything tries to access any of these descriptors, which is hard to avoid. If you have complete control over all reads and writes, there is no need; but opening the file descriptors is way easier than making sure nothing anywhere tries to print a message, emit an error message or diagnostic message, or read standard input.