exit() now calls registered handlers before calling _exit(). And initialize_libc() can now register a handler to close stdout and stderr on program termination!! :)
34 lines
723 B
C++
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);
|
|
} |