歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> 關於Unix >> 一個使用setjmp/longjmp從信號中恢復的小例子

一個使用setjmp/longjmp從信號中恢復的小例子

日期:2017/3/6 15:29:33   编辑:關於Unix
下面這個程序使用setjmp/longjmp和信號處理。這樣,程序在收到一個ctrl-c時 將重新啟動,而不是退出。 #include s td io.h #include signal.h #include setjmp.h jmp_buf buf; void handler(int sig) if (sig == SIGINT) printf(Now got a SIGINT signal\n); 下面這個程序使用setjmp/longjmp和信號處理。這樣,程序在收到一個ctrl-c時
將重新啟動,而不是退出。

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>

jmp_buf buf;

void
handler(int sig)
{
if (sig == SIGINT) printf("Now got a SIGINT signal\n");
longjmp(buf, 1);
/* can't get here */
}

int
main(void)
{
signal(SIGINT, handler);
if (setjmp(buf)) {
printf("back in main\n");
return 0;
} else
printf("first time through\n");
loop:
/* spin here, waiting for ctrl-c */
goto loop;
}
注意:系統並不支持在信號處理程序內部調用庫函數(除非嚴格符合標准所限制的
條件)。這裡只是為了演示方便,實際代碼中不能這樣使用:-)

Copyright © Linux教程網 All Rights Reserved