setjmp与longjmp
后缀jmp指的就是jump,关看名字就能猜到这哥俩是干啥的了。使用他们俩就可以让程序控制流转移,进而实现对异常的处理。
异常处理的结构可以划分为以下三个阶段:
- 准备阶段:在内核栈保存通用寄存器内容
- 处理阶段:保存硬件出错码和异常类型号,然后向当前进程发送信号
- 恢复阶段:恢复保存在内核栈中的各个寄存器内容,返回当前进程的断电处继续执行
过程有点类似递归,只有文字你可能看的有点云里雾里,我们结合一个小例子来看看
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n");
// 跳回setjmp的调用处 - 使得setjmp返回值为1
longjmp(buf, 1);
}
void first(void) {
second();
//这行到不了,因为second里面longjmp已经跳转回去了
printf("first\n");
}
int main() {
int rc;
rc = setjmp(buf);
if (rc==0) {
// 进入此行前,setjmp返回0
first();
}
// longjmp跳转回,setjmp返回1,因此进入此行
else if(rc==1){
printf("main\n");
}
return 0;
}
/*
the ressult as:
second
main
*/
|

现在我们再来看看两个函数的声明:
- setjmp(env) :将程序上下文存储在env中
- longjmp(env,status):env指代setjmp中所保存的函数执行状态变量,status则是作为setjmp的返回值
当然你也可以用switch代替上面的if else,其实try catch就相当于上面的那个函数你可以参考这个实现try catch。
signal信号处理
个人觉得这个在linux下更好用,并且也提供了更多的信号量宏。
下面给出的是signal头文件中的定义
?| 1 2 3 4 5 6 7 |
#define SIGINT 2 // interrupt
#define SIGILL 4 // illegal instruction - invalid function image
#define SIGFPE 8 // floating point exception
#define SIGSEGV 11 // segment violation
#define SIGTERM 15 // Software termination signal from kill
#define SIGBREAK 21 // Ctrl-Break sequence
#define SIGABRT 22 // abnormal termination triggered by abort call
|
这里仅给出维基上的例子
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static void catch_function(int signal) {
puts("Interactive attention signal caught.");
}
int main(void) {
if (signal(SIGINT, catch_function) == SIG_ERR) {
fputs("An error occurred while setting a signal handler.\n", stderr);
return EXIT_FAILURE;
}
puts("Raising the interactive attention signal.");
if (raise(SIGINT) != 0) {
fputs("Error raising the signal.\n", stderr);
return EXIT_FAILURE;
}
puts("Exiting.");
return 0;
}
|
总结
到此这篇关于c语言没有try catch的替代方案的文章就介绍到这了,更多相关c语言try catch内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/AD-milk/archive/2020/06/11/13096666.html








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。