linux的父进程向子进程发kill信号例子以及对子进程的状态进行判断

柔情只为你懂 2022-08-07 12:43 67阅读 0赞

先看一个父进程向子进程发kill信号例子:

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <signal.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. int main(int argc, const char *argv[])
  7. {
  8. pid_t pid;
  9. int status;
  10. pid = fork();
  11. if (0 == pid)
  12. {
  13. printf("Hi, I'm child process!\n");
  14. sleep(10);
  15. }
  16. else if (pid > 0)
  17. {
  18. printf("Send signal to child process (%d)\n", pid);
  19. sleep(1);
  20. kill(pid, SIGABRT);
  21. wait(&status);
  22. if (WIFSIGNALED(status))
  23. {
  24. printf("Child process received singal %d\n", WTERMSIG(status));
  25. }
  26. }
  27. else
  28. {
  29. printf("Fork wrong!\n");
  30. return 1;
  31. }
  32. return 0;
  33. }

判断子进程退出状态的宏:

子进程的结束状态返回后存于status,底下有几个宏可判别结束情况
WIFEXITED(status)如果子进程正常结束则为非0值。
WEXITSTATUS(status)取得子进程exit()返回的结束代码,一般会先用WIFEXITED 来判断是否正常结束才能使用此宏。
WIFSIGNALED(status)如果子进程是因为信号而结束则此宏值为真
WTERMSIG(status)取得子进程因信号而中止的信号代码,一般会先用WIFSIGNALED 来判断后才使用此宏。
WIFSTOPPED(status)如果子进程处于暂停执行情况则此宏值为真。一般只有使用WUNTRACED 时才会有此情况。
WSTOPSIG(status)取得引发子进程暂停的信号代码。

发表评论

表情:
评论列表 (有 0 条评论,67人围观)

还没有评论,来说两句吧...

相关阅读