9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

atexit.c (746B)


      1 #include <u.h>
      2 #include <libc.h>
      3 
      4 #define	NEXIT	33
      5 
      6 static Lock onexlock;
      7 static struct
      8 {
      9 	void	(*f)(void);
     10 	int	pid;
     11 }onex[NEXIT];
     12 
     13 int
     14 atexit(void (*f)(void))
     15 {
     16 	int i;
     17 
     18 	lock(&onexlock);
     19 	for(i=0; i<NEXIT; i++)
     20 		if(onex[i].f == 0) {
     21 			onex[i].pid = getpid();
     22 			onex[i].f = f;
     23 			unlock(&onexlock);
     24 			return 1;
     25 		}
     26 	unlock(&onexlock);
     27 	return 0;
     28 }
     29 
     30 void
     31 atexitdont(void (*f)(void))
     32 {
     33 	int i, pid;
     34 
     35 	pid = getpid();
     36 	for(i=0; i<NEXIT; i++)
     37 		if(onex[i].f == f && onex[i].pid == pid)
     38 			onex[i].f = 0;
     39 }
     40 
     41 void
     42 exits(char *s)
     43 {
     44 	int i, pid;
     45 	void (*f)(void);
     46 
     47 	pid = getpid();
     48 	for(i = NEXIT-1; i >= 0; i--)
     49 		if((f = onex[i].f) && pid == onex[i].pid) {
     50 			onex[i].f = 0;
     51 			(*f)();
     52 		}
     53 	if(s == 0 || *s == 0)
     54 		exit(0);
     55 	exit(exitcode(s));
     56 }