1. Two ways a process can be terminated
A process can be terminated in two different ways.
- the process calls system call _exit(exitCode)
- the process receives a specific signal, like SIGKILL
2. $? is a number represents the terminated child's status
The shell waits for its child processes and put the collected status of the terminated child into $? variable.
Based on how the child was terminated, $? has a different value.
- If the child was terminated by calling _exit(exitCode), $? = exitCode.
- If the child was terminated by a signal, $? = 128 + signalNo
The signalNo is great than 1, so if the child was terminated by a signal, $? > 128.
e.g.
$ cat test.c
#include <unistd.h>
int main(void)
{
_exit(2);
}
$ gcc test.c
$ ./a.out
$ echo $?
2
$ sleep 100
(Press Ctr + C)
$ echo $?
130
3. $? is confusing when it's great than 128
e.g if $? is 130, can you infer how the child was terminated?
Actually, two cases could cause such a result.
- The child called _exit(130)
- The child was terminated by signal SIGINT (the signal no is 2)
To make $? less confusing, applications should NOT exit with a code greater than 128. So developers must bear in mind when writing your new apps.
No comments:
Post a Comment