標籤: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訊號例子以及對子進程的狀態進行判斷