Luna/libs/libc/src/init.cpp
apio 743aedcd49 libc: Implement atexit() and _exit()
exit() now calls registered handlers before calling _exit().

And initialize_libc() can now register a handler to close stdout and stderr on program termination!! :)
2022-10-12 20:41:55 +02:00

34 lines
723 B
C++

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void terminate_libc()
{
fclose(stdout);
fclose(stderr);
}
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"); }
atexit(terminate_libc);
}