- 论坛徽章:
- 0
|
【APUE】8.6. wait and waitpid Functions:
传统上,这两个函数(指wait和waitpid)返回的整数状态是由具体实现方案自己定义的,其中某些bit表示退出状态(对于正常返回),某些bit则用于表示信号的数值(对于非正常返回),一个bit用于表示是否产生了core文件,等等。POSIX.1规定终止状态应该使用<sys/wait.h>中定义的多个宏来查看。其中有4个互斥的宏可以告诉我们进程是如何终止的,它们的名字都以WIF开始。基于这4个宏中的哪个为真,然后再使用其它的宏来取得退出状态,信号数值等信息。
sys/wait.h:
- /*
- * Macros to test the exit status returned by wait and extract the relevant
- * values.
- */
- #if __BSD_VISIBLE
- #define WCOREFLAG 0200
- #endif
- #define _W_INT(i) (i)
- #define _WSTATUS(x) (_W_INT(x) & 0177)
- #define _WSTOPPED 0177 /* _WSTATUS if process is stopped */
- #define WIFSTOPPED(x) (_WSTATUS(x) == _WSTOPPED)
- #define WSTOPSIG(x) (_W_INT(x) >> 8)
- #define WIFSIGNALED(x) (_WSTATUS(x) != _WSTOPPED && _WSTATUS(x) != 0)
- #define WTERMSIG(x) (_WSTATUS(x))
- #define WIFEXITED(x) (_WSTATUS(x) == 0)
- #define WEXITSTATUS(x) (_W_INT(x) >> 8)
- #define WIFCONTINUED(x) (x == 0x13) /* 0x13 == SIGCONT */
- #if __BSD_VISIBLE
- #define WCOREDUMP(x) (_W_INT(x) & WCOREFLAG)
- #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig))
- #define W_STOPCODE(sig) ((sig) << 8 | _WSTOPPED)
- #endif
复制代码
关于wait返回的整数状态中的低8位里面存放的是什么,可以参考以下的内核代码:
sys/libkern/kern/kern_exit.c
- void
- sys_exit(struct thread *td, struct sys_exit_args *uap)
- {
- exit1(td, W_EXITCODE(uap->rval, 0));
- /* NOTREACHED */
- }
复制代码
这应该是进程正常exit的情况,参见W_EXITCODE宏的定义,这里实际上就是把“返回值”
左移8位再或上一个0,所以exit(1)的时候打印出来的int型变量就是256。
sys/libkern/kern/kern_sig.c
- void
- sigexit(td, sig)
- struct thread *td;
- int sig;
- {
- ......
- exit1(td, W_EXITCODE(0, sig));
- }
复制代码
这应该是进程因收到某个信号而终止的情况,调用完W_EXITCODE宏之后,我们所说的int
型状态的低8位里面存储的就是信号,而其它字节则为0。想办法让子进程非正常终止就
可以验证这个情况。 |
|