linux的父進程向子進程發kill訊號例子以及對子進程的狀態進行判斷

來源:互聯網
上載者:User

標籤:linux   kill   多進程   

先看一個父進程向子進程發kill訊號例子:

#include <stdio.h>#include <unistd.h>#include <signal.h>#include <sys/types.h>#include <sys/wait.h>int main(int argc, const char *argv[]){    pid_t pid;    int status;    pid = fork();    if (0 == pid)    {        printf("Hi, I'm child process!\n");        sleep(10);    }    else if (pid > 0)    {        printf("Send signal to child process (%d)\n", pid);        sleep(1);        kill(pid, SIGABRT);        wait(&status);        if (WIFSIGNALED(status))        {            printf("Child process received singal %d\n", WTERMSIG(status));        }    }    else    {        printf("Fork wrong!\n");        return 1;    }    return 0;}


判斷子進程退出狀態的宏:

子進程的結束狀態返回後存於status,底下有幾個宏可判別結束情況
WIFEXITED(status)如果子進程正常結束則為非0值。
WEXITSTATUS(status)取得子進程exit()返回的結束代碼,一般會先用WIFEXITED 來判斷是否正常結束才能使用此宏。
WIFSIGNALED(status)如果子進程是因為訊號而結束則此宏值為真
WTERMSIG(status)取得子進程因訊號而中止的訊號代碼,一般會先用WIFSIGNALED 來判斷後才使用此宏。
WIFSTOPPED(status)如果子進程處於暫停執行情況則此宏值為真。一般只有使用WUNTRACED 時才會有此情況。
WSTOPSIG(status)取得引發子進程暫停訊號代碼。

linux的父進程向子進程發kill訊號例子以及對子進程的狀態進行判斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.