c++ / gcc : segmentation fault at exit of main after catching a signal
The following code triggers a segmentation fault a开发者_JS百科t exit. It seems to happen only if data is allocated on the stack between the 'sigaction' call and the loop :
#include <signal.h>
#include <unistd.h>
bool end = false;
void handler(int) {
end = true;
}
int main() {
struct sigaction sigs;
sigs.sa_handler = handler;
sigaction(SIGINT, &sigs, NULL);
int i;
while (!end)
sleep(1);
return 0;
}
Run and stop with ctrl-C
-> with line 'int i' on : segmentation fault
-> without line 'int i' : exit ok
(compiled with g++ v4.1.1, OS linux kernel 2.6.19)
sounds like a stack release problem ... anyone has an explanation ?
Thanks,
You should initialize all members of your struct sigaction ,as to not risk having it contain garbage, there's flags/etc. in there that alter the behavior of sigaction() Do
struct sigaction args = {};
or
memset(&args,0,sizeof args);
精彩评论