捕获段错误信号的一个简单程序示例:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>void segfault(int dummy) {printf("Help!\n");exit(1);
}int main() {int *p = 0;signal(SIGSEGV, segfault);*p = 17;return 0;
}

如果没有在 segfault 中添加 exit 退出程序,sighandler 会由于非法赋值指令重新执行而一直循环

注释掉 exit 后,一直打印 Help!

栈溢出时 SIGSEGV 信号的处理

上面这个简单的 demo 用于捕获栈溢出时会失败,因为此时已经没有栈空间作为栈帧给 segfault 信号处理函数的调用使用。如果真的需要捕获栈溢出问题,需要首先设定一个可选的栈帧,示例代码如下:

int main() {char myaltstack[SIGSTKSZ];struct sigaction act;stack_t ss;ss.ss_sp = myaltstack;ss.ss_size = sizeof(myaltstack);ss.ss_flags = 0;if (sigaltstack(&ss, NULL))errexit("sigaltstack failed");act.sa_handler = segfault;act.sa_flags = SA_ONSTACK;if (sigaction(SIGSEGV, &act, NULL))errexit("sigaction failed");

以上内容摘自 https://www.win.tue.nl/~aeb/linux/lk/lk-9.html。

man sigaltstack

阅读 sigaltstack 函数的 manual 获取到的使用方法:

  1. 申请一块内存空间作为可选的信号处理函数栈使用
  2. 使用 sigaltstack 函数通知系统可选的信号处理栈帧的存在及其位置
  3. 当使用 sigaction 函数建立一个信号处理函数时,通过指定 SA_ONSTACK 标志通知系统这个信号处理函数应该在可选的栈帧上面执行注册的信号处理函数

manual 中的示例 demo 代码如下:

           stack_t ss;ss.ss_sp = malloc(SIGSTKSZ);if (ss.ss_sp == NULL) {perror("malloc");exit(EXIT_FAILURE);}ss.ss_size = SIGSTKSZ;ss.ss_flags = 0;if (sigaltstack(&ss, NULL) == -1) {perror("sigaltstack");exit(EXIT_FAILURE);}sa.sa_flags = SA_ONSTACK;sa.sa_handler = handler();      /* Address of a signal handler */sigemptyset(&sa.sa_mask);if (sigaction(SIGSEGV, &sa, NULL) == -1) {perror("sigaction");exit(EXIT_FAILURE);}

对 manual 中关键内容的翻译

signaltstack 函数最常见的用法是处理普通程序因为栈溢出而触发的 SIGSEGV 信号的处理过程,在这种情况下 SIGSEGV 信号处理函数不能在进程栈中执行,想要处理这种情况,必须使用一个可选的信号处理栈。

创建一个可选的信号函数执行栈对于那些预期可能会耗尽标准栈的程序非常有用。这种情况是可能发生的,例如因为栈增长的过大触及到了向上增长的堆空间或者栈空间触及到了 setrlimit(RLIMIT_STACK, &rlim) 设定的限制外的内存空间等。

如果标准栈用完,内核将会发送一个 SIGSEGV 信号给程序,在这种情况下捕获这个信号的唯一方式就是使用可选的信号函数执行栈

在可选栈上执行的信号处理函数调用的函数也会使用这个栈空间来执行,当进程切换到该栈帧上执行时,切换完成后接收到的其它的信号,其信号处理函数也将会在这个栈帧上执行。

这个可选栈与标准的栈不同的地方在于,系统并不会动态扩展可选栈的大小。扩展这个可选栈将会带来不可预料的后果。

需要注意的是一个成功的 execve 系统调用将会移除任何存在的可选信号处理栈。一个使用 fork 创建的子进程将会继承父进程的可选信号处理栈的一份配置拷贝

man sigaltstack 的相关信息原文摘录如下:

NAMEsigaltstack - set and/or get signal stack context
SYNOPSIS#include <signal.h>int sigaltstack(const stack_t *ss, stack_t *old_ss);Feature Test Macro Requirements for glibc (see feature_test_macros(7)):sigaltstack():_XOPEN_SOURCE >= 500|| /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L|| /* Glibc versions <= 2.19: */ _BSD_SOURCEDESCRIPTIONsigaltstack()  allows a process to define a new alternate signal stack and/or retrieve the state of an existing alternate signal stack.  An alternate signal stack is used during the execution of a signal handler if the establishment of that handler (see  sigaction(2))  requested it.The normal sequence of events for using an alternate signal stack is the following:1. Allocate an area of memory to be used for the alternate signal stack.2. Use sigaltstack() to inform the system of the existence and location of the alternate signal stack.3. When  establishing  a  signal  handler using sigaction(2), inform the system that the signal handler should be executed on the alternatesignal stack by specifying the SA_ONSTACK flag.The ss argument is used to specify a new alternate signal stack, while the old_ss argument is used to retrieve information about  the  cur‐rently  established  signal stack.  If we are interested in performing just one of these tasks, then the other argument can be specified asNULL.The stack_t type used to type the arguments of this function is defined as follows:typedef struct {void  *ss_sp;     /* Base address of stack */int    ss_flags;  /* Flags */size_t ss_size;   /* Number of bytes in stack */} stack_t;To establish a new alternate signal stack, the fields of this structure are set as follows:ss.ss_flagsThis field contains either 0, or the following flag:SS_AUTODISARM (since Linux 4.7)Clear the alternate signal stack settings on entry to the signal handler.  When the signal handler returns, the previous  al‐ternate signal stack settings are restored.This  flag  was added in order make it safe to switch away from the signal handler with swapcontext(3).  Without this flag, asubsequently handled signal will corrupt the state of the switched-away signal handler.  On kernels where this  flag  is  notsupported, sigaltstack() fails with the error EINVAL when this flag is supplied.ss.ss_spThis  field  specifies the starting address of the stack.  When a signal handler is invoked on the alternate stack, the kernel auto‐matically aligns the address given in ss.ss_sp to a suitable address boundary for the underlying hardware architecture.ss.ss_sizeThis field specifies the size of the stack.  The constant SIGSTKSZ is defined to be large enough to cover the  usual  size  require‐ments for an alternate signal stack, and the constant MINSIGSTKSZ defines the minimum size required to execute a signal handler.To  disable  an existing stack, specify ss.ss_flags as SS_DISABLE.  In this case, the kernel ignores any other flags in ss.ss_flags and theremaining fields in ss.If old_ss is not NULL, then it is used to return information about the alternate signal stack which was in effect  prior  to  the  call  tosigaltstack().  The old_ss.ss_sp and old_ss.ss_size fields return the starting address and size of that stack.  The old_ss.ss_flags may re‐turn either of the following values:SS_ONSTACKThe process is currently executing on the alternate signal stack.  (Note that it is not possible  to  change  the  alternate  signalstack if the process is currently executing on it.)SS_DISABLEThe alternate signal stack is currently disabled.Alternatively,  this value is returned if the process is currently executing on an alternate signal stack that was established usingthe SS_AUTODISARM flag.  In this case, it is safe to switch away from the signal handler with swapcontext(3).  It is  also  possibleto set up a different alternative signal stack using a further call to sigaltstack().SS_AUTODISARMThe alternate signal stack has been marked to be autodisarmed as described above.By specifying ss as NULL, and old_ss as a non-NULL value, one can obtain the current settings for the alternate signal stack without chang‐ing them.RETURN VALUEsigaltstack() returns 0 on success, or -1 on failure with errno set to indicate the error.ERRORSEFAULT Either ss or old_ss is not NULL and points to an area outside of the process's address space.EINVAL ss is not NULL and the ss_flags field contains an invalid flag.ENOMEM The specified size of the new alternate signal stack ss.ss_size was less than MINSTKSZ.EPERM  An attempt was made to change the alternate signal stack while it was active (i.e., the process was already executing on the currentalternate signal stack).NOTESThe  most common usage of an alternate signal stack is to handle the SIGSEGV signal that is generated if the space available for the normalprocess stack is exhausted: in this case, a signal handler for SIGSEGV cannot be invoked on the process stack; if we wish to handle it,  wemust use an alternate signal stack.Establishing an alternate signal stack is useful if a process expects that it may exhaust its standard stack.  This may occur, for example,because the stack grows so large that it encounters the upwardly growing heap, or it reaches  a  limit  established  by  a  call  to  setr‐limit(RLIMIT_STACK, &rlim).  If the standard stack is exhausted, the kernel sends the process a SIGSEGV signal.  In these circumstances theonly way to catch this signal is on an alternate signal stack.On most hardware architectures supported by Linux, stacks grow downward.  sigaltstack() automatically takes account  of  the  direction  ofstack growth.Functions called from a signal handler executing on an alternate signal stack will also use the alternate signal stack.  (This also appliesto any handlers invoked for other signals while the process is executing on the alternate signal stack.)  Unlike the  standard  stack,  thesystem  does  not automatically extend the alternate signal stack.  Exceeding the allocated size of the alternate signal stack will lead tounpredictable results.A successful call to execve(2) removes any existing alternate signal stack.  A child process created via fork(2) inherits  a  copy  of  itsparent's alternate signal stack settings.sigaltstack()  supersedes  the  older  sigstack()  call.  For backward compatibility, glibc also provides sigstack().  All new applicationsshould be written using sigaltstack().History4.2BSD had a sigstack() system call.  It used a slightly different struct, and had the major disadvantage that the caller had to  know  thedirection of stack growth.EXAMPLEThe  following  code segment demonstrates the use of sigaltstack() (and sigaction(2)) to install an alternate signal stack that is employedby a handler for the SIGSEGV signal:stack_t ss;ss.ss_sp = malloc(SIGSTKSZ);if (ss.ss_sp == NULL) {perror("malloc");exit(EXIT_FAILURE);}ss.ss_size = SIGSTKSZ;ss.ss_flags = 0;if (sigaltstack(&ss, NULL) == -1) {perror("sigaltstack");exit(EXIT_FAILURE);}sa.sa_flags = SA_ONSTACK;sa.sa_handler = handler();      /* Address of a signal handler */sigemptyset(&sa.sa_mask);if (sigaction(SIGSEGV, &sa, NULL) == -1) {perror("sigaction");exit(EXIT_FAILURE);}

参考链接:

https://www.win.tue.nl/~aeb/linux/lk/lk-9.html

SIGSEGV 信号的捕获与 sigaltstack 系统调用相关推荐

  1. linux 程序收到sigsegv信号_信号

    当其他方式不起作用时(例如标准输入被冻结),信号是提供低优先级信息和用户与其程序交互的便捷方式.它们允许程序在事件发生时清理或执行操作.有时,程序可以选择忽略受支持的事件.由于处理信号的方式,制作一个 ...

  2. 段违例:sigsegv信号

    sigsegv信号 在调试程序时经常会遇到各种段错误bug导致程序崩溃,用gdb调试发现崩溃的原因通常是因为进程收到了sigsegv信号.即系统报段错误是因为收到了sigsegv信号! 所以在此记录一 ...

  3. linux 程序收到sigsegv信号_linux下定位多线程内存越界问题实践总结

    最近定位了在一个多线程服务器程序(OceanBase MergeServer)中,一个线程非法篡改另一个线程的内存而导致程序core掉的问题.定位这个问题历经曲折,尝试了各种内存调试的办法.往往感觉就 ...

  4. linux SIGSEGV信号

    文章目录 关于SIGSEGV错误及处理方法 https://blog.csdn.net/brace/article/details/1102422 关于SIGSEGV错误及处理方法 今天编程遇到了SI ...

  5. pci数据捕获和信号处理 感叹号_大学毕业设计一席谈之十五 扩频信号的捕获 (1)...

    在本科阶段,这个毕业设计的题目绝对算难的.2018年,我的一位学生敢于挑战,为他点赞.我争取能够深入浅出的讲解这方面的知识. 为什么需要捕获? 捕获是扩频通信系统同步的关键环节,只有当伪码和频率捕获完 ...

  6. linux的基础知识——捕捉SIGCHLD、信号传参,中断系统调用

    文章目录 1.SIGCHLD信号 2.信号传参 3.捕捉信号传参 4.中断系统调用 1.SIGCHLD信号 2.信号传参 3.捕捉信号传参 4.中断系统调用

  7. gps 捕获 matlab,基于FFT的GPS信号快速捕获方法

    基于FFT的GPS信号快速捕获方法 李继忠 李巍 (北京遥感设备研究所,北京100039) 摘要:设计在高动态环境下工作的GPS接收机,其难点之一便在于对卫星伪码的快速捕获. 针对缩短GPS接收机捕获 ...

  8. linux SIGSEGV信号 内存访问错误 Segmentation fault

    linux下程序对SIGSEGV信号的默认处理方式是产生coredump并终止程序,可以参考man 7 signal Signal     Value     Action   Comment ─── ...

  9. m低信噪比下GPS信号的捕获算法研究,分别使用matlab和FPGA对算法进行仿真和硬件实现

    目录 1.算法概述 2.仿真效果预览 3.MATLAB/FPGA部分代码预览 4.完整MATLAB/FPGA程序 1.算法概述 GPS卫星发送的信号一般由3个分量组成:载波.伪码和导航电文,其中伪码和 ...

最新文章

  1. “刷脸”之后 声纹识别有望成为新秀
  2. Boost::context模块fiber的斐波那契测试程序
  3. 四位共阳极数码管显示函数_新手求助四位共阳数码管显示函数
  4. 37 | 案例篇:DNS 解析时快时慢,我该怎么办?
  5. 前端学习(2671): 逻辑实现
  6. 9206-1121-对象数组
  7. HDU 5912 Fraction (2016-ccpc-长春)
  8. TCP协议及TCP正常连接与断开
  9. Java线程之Callable和Future
  10. 微软Windows聚焦锁屏壁纸存放目录
  11. 【学术分享】40个科研学术网站,收藏必备,予取予求!
  12. OpenCV学习Rosenfeld细化算法
  13. 壹度同城新零售系统v4.1.23 社交电商 同城商城
  14. 防屏蔽浏览器_国外lead/emu广告联盟平台/扫盲篇–UA,指纹浏览器与流量来路-VMLogin指纹浏览器介绍..
  15. 机器学习技术:使用深度学习处理文本
  16. unraid 文件服务器,unraid使用记录3——黑群晖安装(包含文件)
  17. USB 传输方式(控制)
  18. Caffe2 - (十六) 创建 LMDB 数据库
  19. 图片损坏打不开如何修复?
  20. Docker 从入门到入坑。

热门文章

  1. 京东云擎(JAE)免费搭建WordPress站点
  2. 骁龙820A高级驾驶辅助系统(ADAS)
  3. Android高仿qq及微信底部菜单的几种实现方式
  4. Microsoft Dynamics CRM 分销行业解决方案
  5. 数据中心制冷系统故障原因及排除方法
  6. 【AWS学习笔记】aws cli 与 aws sdk简介
  7. webapi 访问权限
  8. 临近期末,这些题不来看看吗?(上)
  9. js中表达式 >>> 0 是什么意思
  10. apt-get mysql5.7_在Ubuntu 14.04上安装 MySQL 5.7