Linux fork 後 wait 擷取子進程結束的狀態樣本

來源:互聯網
上載者:User

標籤:linux   c   fork   wait   status   

使用 fork 後,可能需要擷取 fork 的進程的健全狀態,比如有沒有異常、崩潰。
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\n");    fflush(stdout);    if ( (pid = fork()) < 0)    {        printf("fork error\n");    }    else if (pid == 0)    {        printf("after fork, child\n");        // 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\n", WEXITSTATUS(status));    }    else if (WIFSIGNALED(status))    {        printf("abnormal termination, signalstatus = %d\n", WTERMSIG(status), #ifdef WCOREDUMP        WCOREDUMP(status)?"(core file generated)":""); #else         "");#endif    }    else if (WIFSTOPPED(status))    {        printf("child stopped, signal number = %d\n", WSTOPSIG(status));    }    printf("after fork, parent\n");    return 0;}

運行效果:
wait status

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Linux fork 後 wait 擷取子進程結束的狀態樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.