- 论坛徽章:
- 7
|
先说一句题外话:The only portable use of signal() is to set a signal's disposition to SIG_DFL or SIG_IGN. The semantics when using signal() to establish a signal handler vary across systems (and POSIX.1 explicitly permits this variation); do not use it for this purpose.
这句题外话是从 signal 的 man page 中摘抄的,意思是除外你是把 signal 的 handler 设成 SIG_DFL 或者 SIG_IGN,否则最好不要用 signal,而应该用 sigaction。
言归正传,为什么你的程序捕捉不到 SIGSEV 呢?那是因为要捕捉这个信号你的信号处理函数也是要运行的,而你的 SIGSEV 是由于栈溢出产生的,而信号处理函数默认也是在默认栈上运行的,栈溢出了它也一样运行不了。所以解决方案是让信号处理函数不在默认栈上运行,这正好也说明了我们不该用 signal,而应该用 sigaction,因为只有 sigaction 才可以指定 flag,具体例子(在你的例子基础上修改的)如下:- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- static int count=0;
- void handler(int signo)
- {
- printf("count=%d\n", count);
- }
- void test_stack(void)
- {
- char data[1<<20];
- count++;
- test_stack();
- }
- int main ( void )
- { stack_t ss = { . ss_size = SIGSTKSZ }
- ; if ( ( ss . ss_sp = malloc ( SIGSTKSZ ) ) == NULL )
- { perror ( "malloc" )
- ; exit ( EXIT_FAILURE )
- ; }
- if ( sigaltstack ( &ss , NULL ) == -1 )
- { perror ( "sigaltstack" )
- ; exit ( EXIT_FAILURE )
- ; }
- struct sigaction act = { . sa_handler = handler , . sa_flags = SA_ONSTACK } ;
- sigemptyset ( & ( act . sa_mask ) ) ;
- if ( sigaction ( SIGSEGV , & act , NULL ) == -1 )
- perror ( "sigaction" ) ;
- test_stack();
- }
复制代码 |
评分
-
查看全部评分
|