Some people think that the background daemon to do this kind of redirection operations waste resources, we recommend that the 0, 1, 2nd sentence directly closed
Handle down, which is very incorrect. If they are actually closed, some ordinary data file handles will wait
In 0, 1, 2. In the case of a number 2nd handle, some library functions fail to output an error message to the 2nd handle, which breaks
Bad old data.
1, the following code will be stdin, stdout, stderr redirect to/dev/null
Freopen ("/dev/null", "w", stdout);
Freopen ("/dev/null", "W", stderr);
The first way is not always to achieve the goal. Freopen () does not ensure that the new file flow descriptor must reuse the underlying
The original file handle. If not reused, the standard I/O function output to the stderr stream is eventually exported to/dev/null,
But the standard I/O functions that are output to the Stderr_fileno handle are less fortunate and may be exported to some
Can be expected to go in the document. In other words, the number 2nd handle is no longer standard error output at this time. Like what:
Write (2, ...), such a call has a security problem.
2, Apue in the daemon example is done as follows:
Close (0);
Close (1);
Close (2);
Open ("/dev/null", O_RDWR);
DUP (0);
DUP (0);
This approach can avoid the above problems, but there are competitive environment problems.
3, now look at the following code:
int fd = open ("/dev/null", O_RDWR);
* * Handle failure of open () somehow
/
dup2 (FD, 0);
Dup2 (FD, 1);
Dup2 (FD, 2);
if (FD > 2)
{close
(FD);
}
This code is thread-safe compared to the second way.