Luna/libs/libc/src/init.cpp

31 lines
702 B
C++
Raw Normal View History

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void terminate_libc()
{
fclose(stdout);
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()
{
check_for_file(0, &stdout, "/dev/console", "rw");
check_for_file(1, &stderr, "/dev/console", "rw");
atexit(terminate_libc);
}