Exit linux системный вызов

Exit linux системный вызов

Функция exit() приводит к обычному завершению программы, и величина status & 0377 возвращается процессу-родителю (см. wait (2)). Все функции, зарегистрированные с помощью atexit() и on_exit() , вызываются в порядке, обратном порядку регистрации. Все данные всех открытых потоков сохраняются и потоки закрываются. Файлы, созданные функцией tmpfile() удаляются.

Стандарт C описывает два определения EXIT_SUCCESS и EXIT_FAILURE , которые могут быть переданы exit() для обозначения соответственно успешного и неуспешного завершения.

ВОЗВРАЩАЕМЫЕ ЗНАЧЕНИЯ


СООТВЕТСТВИЕ СТАНДАРТАМ


ЗАМЕЧАНИЯ

При обработке выхода возможно зарегистрировать дополнительные функции с помощью atexit и on_exit . Последняя зарегистрированная функция удаляется из очереди и выполняется. Не определено, что произойдет, если во время обработки выхода будет вызвана функция exit() или longjmp() .

Использование EXIT_SUCCESS и EXIT_FAILURE несколько более переносимо (на не-Unix окружения), чем использование 0 и ненулевого значения, например 1 или -1. В часности, VMS использует другое соглашение.

В BSD была произведена попытка стандартизировать коды выхода, см. файл .

После вызова exit() код выхода должен быть передан родительскому процессе. Существует три случая. Если родительский процесс установил SA_NOCLDWAIT или установил обработчик SIGCHLD в SIG_IGN, то код выход игнорируется. Если родительский процесс ожидает дочерний, то он получает уведомление о коде выхода. В обоих случаях завершаемый процесс удаляется немедленно. Если родительский процесс не указал, что он не интересуется кодом выхода дочернего процесса, и при этом он не ожидает его завершения, то завершаемый процесс превращается в «процесс-зомби» (то есть просто контейнер для единственного байта, содержащего код выхода) для того, чтобы родительский процесс мог узнать код выхода, если позднее вызовет одну из функций wait .

Читайте также:  Dr web workstation linux

Если реализация поддерживает сигнал SIGCHLD, то этот сигнал поылается родительскому процессу. Не определено, посылается ли сигнал SIGCHLD родительскому процессу, установившему SA_NOCLDWAIT.

Если процесс является лидером сеанса и его управляющий терминал является управляющим терминалом сеанса, то каждому процессу в группе процессов этого управляющего терминала посылается сигнал SIGHUP, и терминал отсоединяется от этого сеанса, что позволяет захватить его новому управляющему процессу.

Если завершение процесса приводит группу процессов к потере родителя, и если любой член такой группы приостанавливается, то каждому процессу группы посылается сигнал SIGHUP, за которым следует сигнал SIGCONT.

Источник

Exit linux системный вызов

The exit () function causes normal process termination and the value of status & 0377 is returned to the parent (see wait (2)).

All functions registered with atexit (3) and on_exit (3) are called, in the reverse order of their registration. (It is possible for one of these functions to use atexit (3) or on_exit (3) to register an additional function to be executed during exit processing; the new registration is added to the front of the list of functions that remain to be called.) If one of these functions does not return (e.g., it calls _exit (2), or kills itself with a signal), then none of the remaining functions is called, and further exit processing (in particular, flushing of stdio (3) streams) is abandoned. If a function has been registered multiple times using atexit (3) or on_exit (3), then it is called as many times as it was registered.

All open stdio (3) streams are flushed and closed. Files created by tmpfile (3) are removed.

Читайте также:  What is linux mint xfce

The C standard specifies two constants, EXIT_SUCCESS and EXIT_FAILURE , that may be passed to exit () to indicate successful or unsuccessful termination, respectively.

RETURN VALUE


CONFORMING TO


NOTES

It is undefined what happens if one of the functions registered using atexit (3) and on_exit (3) calls either exit () or longjmp (3).

The use of EXIT_SUCCESS and EXIT_FAILURE is slightly more portable (to non-Unix environments) than the use of 0 and some non-zero value like 1 or -1. In particular, VMS uses a different convention.

BSD has attempted to standardize exit codes; see the file .

After exit (), the exit status must be transmitted to the parent process. There are three cases. If the parent has set SA_NOCLDWAIT , or has set the SIGCHLD handler to SIG_IGN , the status is discarded. If the parent was waiting on the child it is notified of the exit status. In both cases the exiting process dies immediately. If the parent has not indicated that it is not interested in the exit status, but is not waiting, the exiting process turns into a «zombie» process (which is nothing but a container for the single byte representing the exit status) so that the parent can learn the exit status when it later calls one of the wait (2) functions.

If the implementation supports the SIGCHLD signal, this signal is sent to the parent. If the parent has set SA_NOCLDWAIT , it is undefined whether a SIGCHLD signal is sent.

If the process is a session leader and its controlling terminal is the controlling terminal of the session, then each process in the foreground process group of this controlling terminal is sent a SIGHUP signal, and the terminal is disassociated from this session, allowing it to be acquired by a new controlling process.

Читайте также:  Linux быстрое копирование файлов

If the exit of the process causes a process group to become orphaned, and if any member of the newly orphaned process group is stopped, then a SIGHUP signal followed by a SIGCONT signal will be sent to each process in this process group.

Источник

Оцените статью
Adblock
detector