libc: Check for file descriptors 0 and 1, and if they exist do not close and reopen them

This commit is contained in:
apio 2022-10-12 20:19:45 +02:00
parent de6041fede
commit be9026442e

View File

@ -6,13 +6,22 @@
extern "C" void initialize_libc() extern "C" void initialize_libc()
{ {
close(0); // If it was already open, close it if (lseek(0, 0, SEEK_CUR) < 0)
close(1); // If it was already open, close it {
errno = 0; // If it was not open. the kernel will throw us EBADF. Let's ignore that, since we don't care. if (errno == EBADF) stdout = fopen("/dev/console", "rw");
stderr = fopen("/dev/console", "rw"); else
if (!stderr) exit(errno); exit(errno);
stdout = fopen("/dev/console", "rw"); if (!stdout) exit(errno);
if (!stdout) exit(errno); errno = 0;
clearerr(stderr); }
clearerr(stdout); else { stdout = fdopen(0, "rw"); }
if (lseek(1, 0, SEEK_CUR) < 0)
{
if (errno == EBADF) stderr = fopen("/dev/console", "rw");
else
exit(errno);
if (!stderr) exit(errno);
errno = 0;
}
else { stderr = fdopen(1, "rw"); }
} }