Thanks for everyone's advice. I 've modified the program as below and
come to these conclusions:
1. signal handler seems not having to register for multiple times,
though the manual sounds like it has to.
2. return from signal handler that catches SIGSEGV is undefined and
cannot go back and recover normal control flow. If we really want to go
back, use long jump.
3. in practice, a signal may be raised at anytime during the execution
of the program, so the signal handler must not call any lib routines
except abort() and _Exit() to keep asynchronous-safe.
reference:
https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal
+handlers
4. The 'long jump in sighandler example' failing to catch the second
SIGSEGV, even if the handler is registered for the second time, seems
still weird to me. I guess this is beyond the explaination of ANSI C.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <setjmp.h>
#define MYSIG SIGINT
#define y main
jmp_buf buf;
volatile sig_atomic_t i=0;
void sighandler(int a){
longjmp(buf, ++i);
}
int x(){
if(signal(MYSIG, sighandler)==SIG_ERR){
perror("error signal");
abort();
}
int *a=NULL;
switch(setjmp(buf)){
case 0:
case 1:
puts("First time caught.");
#if 1
if(SIG_ERR==signal(MYSIG, sighandler))
return;
#endif
raise(MYSIG);
getchar();
*a=1;
break;
default:
puts("Second time caught.");
}
}
volatile sig_atomic_t j=0;
void sighandler2(int a){
++j;
}
int y(){
if(signal(MYSIG, sighandler2)==SIG_ERR){
perror("error signal");
abort();
}
int *a=NULL;
while(1){
switch(j){
case 0:
raise(MYSIG);
//getchar(); // press ctrl+c here
//*a=10;
break;
case 1:
puts("First time caught.");
#if 0
if(SIG_ERR==signal(MYSIG, sighandler2))
return;
#endif
raise(MYSIG);
//getchar();
//*a=10;
break;
default:
puts("Second time caught.");
return;
}
}
}
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|