Why don't I get an infinite loop when I call exit from an atexit handler?

225 views Asked by At

This program register a function calling exit() with atexit().

#include <stdio.h>
#include <stdlib.h>

void machiavellian() {
    puts("At exit");
    exit(0);
}
int main(void) {
    atexit(machiavellian);
    exit(0);
}

From man atexit

These callbacks must not call exit()

I was awaiting an infinite loop, but instead, it only calls once machiavellian(). What happens?

$ make you_cant_exit_me
cc     you_cant_exit_me.c   -o you_cant_exit_me
$ ./you_cant_exit_me 
At exit
$ echo $?
0
1

There are 1 answers

1
Sneftel On BEST ANSWER

"These callbacks must not call exit()" does not mean "If these callbacks call exit(), special interesting things will happen". It just means "don't do it, or you're on your own". It's possible that a different POSIX-compliant system will do something else, like an infinite loop. Since you didn't follow the rules, you can't count on what will happen.

(I would assume that few if any systems would get into an infinite loop, though. It's trivial to avoid that, and I can't imagine it being a useful result.)