Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

c - Why signal handler goes to infinite loop? - SIGSEGV

Any idea why the signal handler goes to infinite loop?

Here is the code. Please help me.

enter code here
 9 void SIGSEGV_handler(int signal)
10 {
11  printf("Segmentation fault caught....
");
12  printf("Value of instance variable: i = %d

", i);
13 } 
16 
17 int main()
18 {
19  char *mallocPtr, *callocPtr, *reallocPtr, *memalignPtr, *vallocPtr;
20  struct sigaction sa;
21 
22  sa.sa_handler=SIGSEGV_handler;
23  sigaction(SIGSEGV, &sa, NULL);
24 
37 
38  printf("The segmentation fault handler will be entered for i = 3, 4, 5 and 6
");
39 
40 
41  for(i=0; i<7; i++)
42   {
43    printf("i = %d
",i);
44 
45    mallocPtr=(char*)malloc(3);
46    printf("Malloc address : %x
",mallocPtr);
47    strcpy(mallocPtr, "Hhvhgvghsvxhvshxv");
48    puts(mallocPtr);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default action for SIGSEGV is to terminate your process. But you install a handler and override this:

/* Does nothing to "fix" what was wrong with the faulting
 * instruction.
 */
void SIGSEGV_handler(int signal)
{
    printf("Segmentation fault caught....
");
    printf("Value of instance variable: i = %d

", i);
}

So for every instruction that triggers a sigsegv, this handler is called and the instruction is restarted. But your handler did nothing to fix what was wrong in the first place with the faulting instruction.

In conclusion, when the instruction is restarted, it will fault again. And again, and again and... you get the idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...