24 Ocak 2018 Çarşamba

std::exit

Giriş
Açıklaması şöyle.
exit terminates the process normally, performing the regular cleanup for terminating programs.
Normal program termination performs the following (in the same order): Objects associated with the current thread with thread storage duration are destroyed (C++11 only). Objects with static storage duration are destroyed (C++) and functions registered with atexit are called. All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed. Control is returned to the host environment.
Note that objects with automatic storage are not destroyed by calling exit (C++).
Ancak yine de std::exit'e güvenmeyip kendimiz kaynakları kapatsak daha iyi olabilir.

exit'e Verilen Değer
POSIX açısından açıklaması şöyle. 8 bit 0-255 arasında bir değer olması gerekir.
The value of status may be 0EXIT_SUCCESSEXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available from wait() and waitpid(); the full value shall be available from waitid() and in the siginfo_t passed to a signal handler for SIGCHLD.
Aslında std::exit altta _exit() sistem çağrısı yapar. Bu çağrı int değer alabilir. Açıklaması şöyle.
The number passed to the _exit() system call is of type int, so a 32bit integer with values from -2147483648 (-231) to 2147483647 (231-1).

However, on all systems, when the parent process (or the child subreaper or init if the parent died) uses the wait(), waitpid(), wait3(), wait4() system calls to retrieve it, only the lower 8 bits of it are available (values 0 to 255).
Global Objects
Açıklaması şöyle
Destructors of the global objects are called by std::exit. That function is called by the C++ run-time when main returns.
std::exit()'i başka bir thread içinde çağırabiliriz. Şöyle yaparız.
struct A
{
    A() { std::cout << std::this_thread::get_id() << '\n'; }
    ~A() { std::cout << std::this_thread::get_id() << '\n'; }
};

A a;

int main() {
    std::thread([]() { std::exit(0); }).join();
}
Çıktı olarak şunu alırız.
140599080433472
140599061243648




Hiç yorum yok:

Yorum Gönder