判断进程是否正常退出

//judge_wait.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc,char* argv[])
{
	pid_t pid,w_pid;
	int sta;
	pid = fork();
	if(pid == -1){
		perror("fork error");
		exit(1);
	}else if(pid == 0){
		printf("I am child.\n");
		execlp("./test","test",NULL);
		sleep(5);
		exit(73);
	}else{
		w_pid = wait(&sta);
		if(w_pid == -1){
			perror("wait error");
			exit(1);
		}
		// 进程正常退出,获取进程正常退出状态
		if(WIFEXITED(sta) !=0){
			printf("%d \n",WEXITSTATUS(sta));
		}
		//进程异常终止,获取使进程异常终止的信号
		if(WIFSIGNALED(sta)){
			printf("%d \n",WTERMSIG(sta));
		}
	}
	
	return 0;
}


/*
测试程序异常退出
tesst.c
*/
main(int argc,char* argv[])
{
	char *ptr = "jasgfhjgalklsjf";
	
	//ptr[1] = "e";
	int a =5 / 0;
	
	return 0;
	
}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您的问题是如何实现fork创建三个子进程,其中一个子进程出现段错误,一个子进程浮点数除外,一个子进程正常退出。 首先,使用fork函数创建三个子进程: ```c #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { pid_t pid1, pid2, pid3; pid1 = fork(); if (pid1 < 0) { printf("Error: fork process 1 failed.\n"); exit(1); } else if (pid1 == 0) { // 第一个子进程 int *p = NULL; *p = 1; exit(0); } pid2 = fork(); if (pid2 < 0) { printf("Error: fork process 2 failed.\n"); exit(1); } else if (pid2 == 0) { // 第二个子进程 float a = 1.0, b = 0.0; float c = a / b; exit(0); } pid3 = fork(); if (pid3 < 0) { printf("Error: fork process 3 failed.\n"); exit(1); } else if (pid3 == 0) { // 第三个子进程 exit(0); } // 父进程 int status1, status2, status3; waitpid(pid1, &status1, 0); waitpid(pid2, &status2, 0); waitpid(pid3, &status3, 0); if (WIFEXITED(status1)) { printf("Child process 1 exited normally with status: %d\n", WEXITSTATUS(status1)); } else if (WIFSIGNALED(status1)) { printf("Child process 1 exited abnormally with signal: %d\n", WTERMSIG(status1)); } if (WIFEXITED(status2)) { printf("Child process 2 exited normally with status: %d\n", WEXITSTATUS(status2)); } else if (WIFSIGNALED(status2)) { printf("Child process 2 exited abnormally with signal: %d\n", WTERMSIG(status2)); } if (WIFEXITED(status3)) { printf("Child process 3 exited normally with status: %d\n", WEXITSTATUS(status3)); } else if (WIFSIGNALED(status3)) { printf("Child process 3 exited abnormally with signal: %d\n", WTERMSIG(status3)); } return 0; } ``` 在上述代码中,我们使用了三次fork函数创建了三个子进程。第一个子进程出现了一个段错误,第二个子进程进行了一个浮点数除法运算,第三个子进程正常退出。 使用waitpid函数等待子进程结束,并通过WIFEXITED和WIFSIGNALED函数判断进程的结束状态。 希望这个回答能够帮到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值