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

StackOverflow https://stackoverflow.com/questions/20446384

  •  30-08-2022
  •  | 
  •  

문제

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
도움이 되었습니까?

해결책

"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.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top