开发者

SIGINT signal()/sigaction in C++

So here is my code:

void sigHandle(int sig)
{
    signal(SIGINT, sigHandle);    //Is this line necessairy?
    cout<<"Signal: "<<sig<<endl;    
}

int main(){

    signal(SIGINT, sigHandle);

    while(true){ //Supposed to loop until user exits.

    //rest of my code
    
    }
}

Now it is my understanding of signal() that when the SIGINT command (Ctrl+C right?) is received my function sigHandle should be called with an integer value of 2 (the SIGINT number), the method should run and the program should NOT exit.

All I would like to do is just print the signal number and move on, however after printing out "Signal: 2" it exits.

(Eventually I'm supposed to handle the first 32 interrupts but I figured Ctrl+C would be the most difficult so I'm starting here.)

In main if I do signal(SIGINT, SIG_IGN); it ignores the signal correctly and doesn't exit but I now have no way of knowing if I recieved the SIGINT interrupt.

Earlier I was playing around with the sigaction struct but I could not find any real comprehensive documentation on it so I decided to go with just "raw" signal handling.

This was my sigaction code (same problem as above):

struct sigaction action;
action.sa_handler = sigHandle;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGINT, &action, 0);

Thanks for your help!

EDIT

OK SO After many many many hours of scowering through man pages and the internet I have happened across a (very) ghetto solution involving saving the stack pre-infinite loop then when the interrupt comes, doing what I need to do, then re-setting the stack back to where it was and calling the sigrelse() command to re-set any states that might have been changed and not re-loaded.

I understand that this is not the most elegant/efficient/or even socially acceptable solution to this problem but it works and as far as I can tell I am not leaking any memory anywhere so it's all good...

I am st开发者_如何转开发ill looking for a solution to this problem and I view my stack re-setting shenanigins as only a temporary fix...

Thanks!


Also note you should not call stdio (or other non-reentrant functions) in signal handlers. (your signal handler might be invoked in the middle of a malloc or it's C++ equivalent)


It is not. You just replacing SIGINT's handles with same function. How does you program perform wait?

If you have something like:

int main
{ 
 // ...

  int r = read(fd, &buff, read_size); // your program hangs here, waiting for the data.
                                      // but if signal occurred during this period of time
                                      // read will return immediately, and r may != read_size

  return 0;  // then it will go straight to return.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜