Remove all fclose with stdin, stdout and stderr

since it is wrong to close the builtin stream and specially note
https://pubs.opengroup.org/onlinepubs/9699919799/functions/fclose.html:

Since after the call to fclose() any use of stream results in
undefined behavior, fclose() should not be used on stdin, stdout,
or stderr except immediately before process termination (see XBD
Process Termination), so as to avoid triggering undefined behavior
in other standard interfaces that rely on these streams. If there
are any atexit() handlers registered by the application, such a
call to fclose() should not occur until the last handler is
finishing. Once fclose() has been used to close stdin, stdout, or
stderr, there is no standard way to reopen any of these streams.

and it is also unnecessary because the stream always get flushed.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
This commit is contained in:
Xiang Xiao 2020-10-13 16:08:01 +08:00 committed by Masayuki Ishikawa
parent a12a79fdb3
commit e160bffe28
1 changed files with 3 additions and 18 deletions

View File

@ -133,11 +133,10 @@ int daemon(int nochdir, int noclose)
}
#ifdef CONFIG_FILE_STREAM
/* Make sure the stdin, stdout, and stderr are closed */
/* Make sure the stdout, and stderr are flushed */
fclose(stdin);
fclose(stdout);
fclose(stderr);
fflush(stdout);
fflush(stderr);
#endif
/* Dup the fd to create standard fd 0-2 */
@ -145,20 +144,6 @@ int daemon(int nochdir, int noclose)
dup2(fd, 1);
dup2(fd, 2);
/* fdopen to get the stdin, stdout and stderr streams. The
* following logic depends on the fact that the library layer
* will allocate FILEs in order. And since we closed stdin,
* stdout, and stderr above, that is what we should get.
*
* fd = 0 is stdin (read-only)
* fd = 1 is stdout (write-only, append)
* fd = 2 is stderr (write-only, append)
*/
fdopen(0, "r");
fdopen(1, "a");
fdopen(2, "a");
/* We can close the original file descriptor now (unless it was
* one of* 0-2)
*/