文章图片
概览
使用 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年后停产,它在全球在线商店中都买不到
- 新品上架后没流量没转化?来看看这些操作步骤和流程都做对了没!
- 先敬罗衣后敬人,互联网时代,要不要打造人设?