libc: cleanup atexit and put exits() in its own compilation unit

this avoids having to pull in atexit() and its dependencies
(lock(), unlock()) into every program. (as exits() is called
by _main() from main9.s).
This commit is contained in:
cinap_lenrek 2017-10-20 20:58:38 +02:00
parent 67d9c6b2f9
commit e3d8fe9d4a
4 changed files with 37 additions and 26 deletions

View file

@ -14,7 +14,6 @@ void exits(char *msg)
.PP
.B
int atexit(void(*)(void))
.PP
.B
void atexitdont(void(*)(void))
.fi
@ -75,6 +74,8 @@ returns 0 if that limit has been reached.
.I Atexitdont
cancels a previous registration of an exit function.
.SH SOURCE
.B /sys/src/libc/port/exits.c
.br
.B /sys/src/libc/port/atexit.c
.SH "SEE ALSO"
.IR fork (2),

View file

@ -1,7 +1,7 @@
#include <u.h>
#include <libc.h>
#define NEXIT 33
extern void (*_onexit)(void);
typedef struct Onex Onex;
struct Onex{
@ -10,16 +10,31 @@ struct Onex{
};
static Lock onexlock;
Onex onex[NEXIT];
static Onex onex[33];
static void
onexit(void)
{
int i, pid;
void (*f)(void);
pid = getpid();
for(i = nelem(onex)-1; i >= 0; i--)
if((f = onex[i].f) != nil && onex[i].pid == pid) {
onex[i].f = nil;
(*f)();
}
}
int
atexit(void (*f)(void))
{
int i;
_onexit = onexit;
lock(&onexlock);
for(i=0; i<NEXIT; i++)
if(onex[i].f == 0) {
for(i=0; i<nelem(onex); i++)
if(onex[i].f == nil) {
onex[i].pid = getpid();
onex[i].f = f;
unlock(&onexlock);
@ -35,26 +50,7 @@ atexitdont(void (*f)(void))
int i, pid;
pid = getpid();
for(i=0; i<NEXIT; i++)
for(i=0; i<nelem(onex); i++)
if(onex[i].f == f && onex[i].pid == pid)
onex[i].f = 0;
onex[i].f = nil;
}
#pragma profile off
void
exits(char *s)
{
int i, pid;
void (*f)(void);
pid = getpid();
for(i = NEXIT-1; i >= 0; i--)
if((f = onex[i].f) && pid == onex[i].pid) {
onex[i].f = 0;
(*f)();
}
_exits(s);
}
#pragma profile on

13
sys/src/libc/port/exits.c Normal file
View file

@ -0,0 +1,13 @@
#include <u.h>
#include <libc.h>
void (*_onexit)(void);
#pragma profile off
void
exits(char *s)
{
if(_onexit != nil) (*_onexit)();
_exits(s);
}

View file

@ -22,6 +22,7 @@ CFILES=\
ctype.c\
encodefmt.c\
execl.c\
exits.c\
exp.c\
fabs.c\
floor.c\