libc: Make the stdio initialization code cleaner

This commit is contained in:
apio 2022-10-14 19:36:20 +02:00
parent 4e08c9d8ce
commit ccf8f404a8

View File

@ -10,25 +10,22 @@ static void terminate_libc()
fclose(stderr);
}
static void check_for_file(int fd, FILE** target_stream, const char* path, const char* mode)
{
if (lseek(fd, 0, SEEK_CUR) < 0)
{
if (errno == EBADF) *target_stream = fopen(path, mode);
else
exit(errno);
if (!*target_stream) exit(errno);
errno = 0;
}
else { *target_stream = fdopen(fd, mode); }
}
extern "C" void initialize_libc()
{
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"); }
check_for_file(0, &stdout, "/dev/console", "rw");
check_for_file(1, &stderr, "/dev/console", "rw");
atexit(terminate_libc);
}