linux 获取子进程,Linux fork 后 wait 获取子进程结束的状态示例

本文介绍如何通过wait系统调用来获取子进程的状态变化信息,包括正常终止、异常终止及被信号停止的情况,并提供了一个C语言示例程序,演示了不同情况下子进程的状态获取方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 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

#include

#include

#include

#include

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;

}

运行效果:

L3Byb3h5L2h0dHAvd3Jjb2RlLmNvbS9pbWFnZXMvTGludXgtZm9yay0lRTUlOTAlOEUtd2FpdC0lRTglOEUlQjclRTUlOEYlOTYlRTUlQUQlOTAlRTglQkYlOUIlRTclQTglOEIlRTclQkIlOTMlRTYlOUQlOUYlRTclOUElODQlRTclOEElQjYlRTYlODAlODElRTclQTQlQkElRTQlQkUlOEIucG5n.jpgwait

status

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 06-29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值