Normally, a process terminates in one of two ways.
Either the executing program calls the exit function, or the program's main function returns. The exit code is the argument passed to the exit function, or the value returned from main. The exit function
terminates execution of the current program,
closes any open file descriptors,
and returns the lower eight bits of the value status to the parent process to retrieve using the wait family of functions.
The parent process will receive a SIGCHLD signal. Any child processes' parent process id will be changed to 1 (init).
The exit() function will call the system call _exit(), which may be called directly to bypass the exit handlers.
A process may also terminate abnormally, in response to a signal.
SIGBUS, SIGSEGV, and SIGFPE signals cause the process to terminate.
Other signals are used to terminate a process explicitly.
The SIGINT signal is sent to a process when the user attempts to end it by typing Ctrl+C in its terminal.
The SIGTERM signal is sent by the kill command.
The default disposition for both of these is to terminate the process.
By calling the abort function, a process sends itself the
SIGABRT signal, which terminates the process and produces a core file.
The most powerful termination signal is SIGKILL, which ends a process immediately and cannot be blocked or handled by a program.
$ kill -KILL pid
$ man kill
To send a signal from a program, use the kill function. Include the
and
headers if you use the kill function.
With most shells, it's possible to obtain the exit code of the most recently executed program using the special $? variable.
$ ls /
$ echo $?
0
$ ls bogusfile
ls: bogusfile: No such file or directory
$ echo $?
1
You should use exit codes only between zero and 127. Exit codes above 128 have a special meaning-when a process is terminated by a signal, its exit code is 128 plus the signal number.