c++ / gcc : 捕获信号后 main 退出时出现分段错误
以下代码在退出时触发分段错误。 似乎只有当数据在“sigaction”调用和循环之间的堆栈上分配时才会发生:
#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;
}
使用 ctrl-C
-> 运行并停止'int i' 行打开:分段错误
->没有行 'int i' : exit ok
(用 g++ v4.1.1 编译,操作系统 linux 内核 2.6.19)
听起来像是堆栈释放问题......有人有解释吗?
谢谢,
The following code triggers a segmentation fault at 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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该初始化 struct sigaction 的所有成员,以免冒着包含垃圾、标志等的风险。在那里改变 sigaction() 的行为
做
或
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
or