The problem of redirecting Stdin,stdout,stderr to/dev/null in the daemon daemon

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: