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()
{
close(0); // If it was already open, close it
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.
stderr = fopen("/dev/console", "rw");
if (!stderr) exit(errno);
stdout = fopen("/dev/console", "rw");
if (!stdout) exit(errno);
clearerr(stderr);
clearerr(stdout);
if (lseek(0, 0, SEEK_CUR) < 0)
{
if (errno == EBADF) stdout = fopen("/dev/console", "rw");
else
exit(errno);
if (!stdout) exit(errno);
errno = 0;
}
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"); }
}