《Unix环境高级编程》:演示不同的exit值

《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。


程序简介:这个程序演示了不同的EXIT值,并打印出相关信息


//《APUE》程序8-3:打印exit状态说明
//《APUE》程序8-4:演示不同的exit值
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

void pr_exit(int status);
void error_quit(const char *str);

int main(void)
{
	pid_t pid;
	int status;

	pid = fork();
	if( pid < 0 )
		error_quit("fork error");
	//子线程直接退出
	else if( pid == 0 )
		exit(7);

	if( wait(&status) != pid )
		error_quit("wait error");
	pr_exit(status);

	pid = fork();
	if( pid < 0 )
		error_quit("fork error");
	//产生SIGART信号
	else if( pid == 0 )
		abort();

	//等待子进程退出
	if( wait(&status) != pid )
		error_quit("wait error");
	pr_exit(status);

	pid = fork();
	if( pid < 0 )
		error_quit("fork error");
	//除数为0,产生SIGFPE信号
	else if( pid == 0 )
		status /= 0;

	//等待子进程退出
	if( wait(&status) != pid )
		error_quit("wait error");
	pr_exit(status);
	return 0;
}

//输出错误信息并退出
void error_quit(const char *str)
{
	fprintf(stderr, "%s\n", str);
	exit(1);
}

void pr_exit(int status)
{
	if( WIFEXITED(status) )
	{
		printf("normal termination, exit status = %d\n", 
			WEXITSTATUS(status));
	}
	else if( WIFSIGNALED(status) )
	{
		printf("abnormal termination, signal number = %d%s\n", 
			WTERMSIG(status),
#ifdef WCOREDUMP
			//no的输出是我加上去的
			//这里不知为什么,输出的结果和书上说的不一样
			WCOREDUMP(status) ? " (core file gererated)" : " no ");
#else
			"");
#endif
	}
	else if( WIFSTOPPED(status) )
	{
		printf("child stopped, signal number = %d\n", 
			WSTOPSIG(status));
	}
}


运行示例(红色字体的为输入):

qch@ubuntu:~/code$gcc temp.c -o temp
temp.c: In function ‘main’:
temp.c:43: warning: division by zero
qch@ubuntu:~/code$ ./temp
normal termination, exit status = 7
abnormal termination, signal number = 6 no 
abnormal termination, signal number = 8 no 


注意:不知为什么在我的电脑上,WCOREDUMP宏的返回结果与书上说的不一样,这个问题以后要研究一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值