
文章圖片
概覽
使用 fork 后 , 可能需要獲取 fork 的進程的運行狀況 , 比如有沒有異常、崩潰 。
【Linux fork 后 wait 獲取子進程結束的狀態示例】wait 在 man 中關鍵的描述如下:
All of these system calls are used to wait for state changes in a child of the calling process and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal.
示例代碼#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int status;
printf(\"before fork\\");
fflush(stdout);
if ( (pid = fork()) < 0)
{
printf(\"fork error\\");
else if (pid == 0)
{
printf(\"after fork child\\");
// 4種測試情況
exit(7); // -> normal termination exitstatus = 7
// abort(); // -> abnormal termination signalstatus = 6 (SIGABRT)
// int i = 1 / 0; // -> abnormal termination signalstatus = 8 (SIGFPE)
// char *p = NULL; *p = 'a'; // -> abnormal termination signalstatus = 11 (SIGSEGV)
wait(&status);
if (WIFEXITED(status))
{
printf(\"normal termination exitstatus = %d\\" WEXITSTATUS(status));
else if (WIFSIGNALED(status))
{
printf(\"abnormal termination signalstatus = %d\\" WTERMSIG(status)
#ifdef WCOREDUMP
WCOREDUMP(status)?\"(core file generated)\":\"\");
#else
\"\");
#endif
else if (WIFSTOPPED(status))
{
printf(\"child stopped signal number = %d\\" WSTOPSIG(status));
printf(\"after fork parent\\");
return 0;
運行效果
推薦閱讀
- 熱鬧!小米、一加和iQOO新機將在10月的最后一周發布
- 升級HarmonyOS NEXT公測版后,我發現應用適配速度超出預期!
- 消費降級后才知道,5種家電“用不起”,別被低廉的售價迷惑了
- 西方競爭不過中國就污蔑,抄完作業后,不吱聲了
- 天璣9400正式發布!能效創新高,中國技術從落后到穩居世界第一
- 與海信、三星合作后 德國高端電視品牌LOEWE進軍投影行業
- 十一國內格局突變,蘋果后勁不足,小米沖到第三
- 蘋果USB超級硬盤可能在16年后停產,它在全球在線商店中都買不到
- 新品上架后沒流量沒轉化?來看看這些操作步驟和流程都做對了沒!
- 先敬羅衣后敬人,互聯網時代,要不要打造人設?
