[Linux C] signal 的使用

news2024/9/22 5:37:28

前言:

signal 是一种通信机制,可以跨进程发送,可以同进程跨线程发送,可以不同进程向指定线程发送。

信号的创建有两套api,一个是signal,一个是sigaction,signal缺陷很多,比如没有提供触发后自动再次设置处理信号处理策略,这会导致连续触发的两个信号,一个进入了期待的信号处理流程,另外一个则进入了默认的信号处理流程。

信号的递送和接受处理是异步的,即信号发送者不会因为信号接收者使用了阻塞信号处理函数而被阻塞住。但是信号的递送可能会出现阻塞,这个阻塞发生在信号发送者把信号送入内核的信号队列中(需要从代码层面验证)。

信号处理方式:

信号的处理有三种方式:默认,忽略,信号处理函数,可以在使用 sigaction 创建信号处理策略时指定。

默认分为如下几种:

       Term   Default action is to terminate the process.

       Ign    Default action is to ignore the signal.

       Core   Default action is to terminate the process and dump core (see core(5)).

       Stop   Default action is to stop the process.

       Cont   Default action is to continue the process if it is currently stopped.

不同信号的默认行为如下:

       Signal      Standard   Action   Comment  ────────────────────────────────────────────────────────────────────────
       SIGABRT      P1990      Core    Abort signal from abort(3)
       SIGALRM      P1990      Term    Timer signal from alarm(2)
       SIGBUS       P2001      Core    Bus error (bad memory access)
       SIGCHLD      P1990      Ign     Child stopped or terminated
       SIGCLD         -        Ign     A synonym for SIGCHLD
       SIGCONT      P1990      Cont    Continue if stopped
       SIGEMT         -        Term    Emulator trap
       SIGFPE       P1990      Core    Floating-point exception
       SIGHUP       P1990      Term    Hangup detected on controlling terminal or death of controlling process
       SIGILL       P1990      Core    Illegal Instruction
       SIGINFO        -                A synonym for SIGPWR
       SIGINT       P1990      Term    Interrupt from keyboard
       SIGIO          -        Term    I/O now possible (4.2BSD)
       SIGIOT         -        Core    IOT trap. A synonym for SIGABRT
       SIGKILL      P1990      Term    Kill signal
       SIGLOST        -        Term    File lock lost (unused)
       SIGPIPE      P1990      Term    Broken pipe: write to pipe with no readers; see pipe(7)
       SIGPOLL      P2001      Term    Pollable event (Sys V). Synonym for SIGIO
       SIGPROF      P2001      Term    Profiling timer expired
       SIGPWR         -        Term    Power failure (System V)
       SIGQUIT      P1990      Core    Quit from keyboard
       SIGSEGV      P1990      Core    Invalid memory reference
       SIGSTKFLT      -        Term    Stack fault on coprocessor (unused)
       SIGSTOP      P1990      Stop    Stop process
       SIGTSTP      P1990      Stop    Stop typed at terminal
       SIGSYS       P2001      Core    Bad system call (SVr4); see also seccomp(2)
       SIGTERM      P1990      Term    Termination signal
       SIGTRAP      P2001      Core    Trace/breakpoint trap
       SIGTTIN      P1990      Stop    Terminal input for background process
       SIGTTOU      P1990      Stop    Terminal output for background process
       SIGUNUSED      -        Core    Synonymous with SIGSYS
       SIGURG       P2001      Ign     Urgent condition on socket (4.2BSD)
       SIGUSR1      P1990      Term    User-defined signal 1
       SIGUSR2      P1990      Term    User-defined signal 2
       SIGVTALRM    P2001      Term    Virtual alarm clock (4.2BSD)
       SIGXCPU      P2001      Core    CPU time limit exceeded (4.2BSD); see setrlimit(2)
       SIGXFSZ      P2001      Core    File size limit exceeded (4.2BSD); see setrlimit(2)
       SIGWINCH       -        Ign     Window resize signal (4.3BSD, Sun)

通过pthread_kill进行线程间信号传递

信号可以时线程级别的,可以通过 pthread_kill 给同进程的其他线程发信号,可以通过 tgkill 给其他进程的指定线程发信号,通过 raise 可以给当前线程发信号。

Demo:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>

pthread_t newtid;

void usrHandler(int signum,siginfo_t *info,void *ucontext)
{
  printf("[SIGUSR1 handler thread] tid -> %d , ready to send SIGUSR2 to child thread \n",gettid());
  pthread_kill(newtid,SIGUSR2);
  printf("[SIGUSR1 handler thread] tid -> %d , SIGUSR2 sent out \n",gettid());
}

void usrHandler2(int signum,siginfo_t *info,void *ucontext)
{
  printf("[SIGUSR2 handler thread] tid -> %d , %d , SIGUSR2 received \n",gettid(),signum);
}

void* threadRoutine(void* arg)
{
  pthread_t tid = *(pthread_t*)arg;
  printf("[new thread] tid -> %d , arg -> %d \n",gettid(),tid);

  // set SIGSUR2
  sigset_t mask2;
  sigemptyset(&mask2);

  struct sigaction act2;
  memset(&act2,0x0,sizeof(struct sigaction));
  struct sigaction oldact2;
  memset(&oldact2,0x0,sizeof(struct sigaction));

  act2.sa_sigaction = usrHandler2;
  act2.sa_mask = mask2;
  act2.sa_flags = 0; //no flag is set
  sigaction(SIGUSR2, &act2, &oldact2);

  while(1) {;}
}

int main(int argc,char** argv)
{
  printf("[main thread] tid -> %d \n",gettid());
// set SIGUSR1
  sigset_t mask;
  sigemptyset(&mask);

  struct sigaction act;
  memset(&act,0x0,sizeof(struct sigaction));
  struct sigaction oldact;
  memset(&oldact,0x0,sizeof(struct sigaction));

  act.sa_sigaction = usrHandler;
  act.sa_mask = mask;
  act.sa_flags = 0; //no flag is set
  sigaction(SIGUSR1, &act, &oldact);

  pthread_t maintid = gettid();
  pthread_create(&newtid,NULL,&threadRoutine,(void*)&maintid);

  sleep(2);

  while(1) {
    raise(SIGUSR1);
    sleep(2);
  }
}

上面的例子中,主线程会循环给自己发信号 SIGUSR1 ,在信号处理函数中会给子线程发送 SIGUSR2。

当子线程通过pthread_kill给主线程发送信号时,会产生 SIGSEGV, 具体原因不明,如果有类似情况,可以参考如下:

pthread_kill引发的争论 - 简书最近提测的一段代码中有一个,遇到一个诡异的bug,总是崩溃在pthread_kill这个函数上,并且不是每次比现。调用逻辑大致如下,利用pthread_kill判断一个线程是...icon-default.png?t=N7T8https://www.jianshu.com/p/756240e837dd

ps:可以通过 pause 挂起当前线程,直到等到一个信号为止;可以通过 sigsuspend 挂起当前线程,直到等到某些信号为止。

管理mask

每个线程都有自己的mask,可以通过pthread_sigmask来管理。

通过mask进行信号block

使用sigaction创建信号处理策略时指定mask。被列入mask集合中的signal会被阻塞,直到阻塞信号的动作结束,这些信号会被继续投递到信号处理逻辑中。

比如通过sigaction 指定 “当发生SIGUSR1的时候,阻塞所有SIGUSR2”,那么如果 SIGUSR1 的信号处理函数耗时较长,那么 SIGUSR2 会一直等到 SIGUSR1 的处理函数走完才会被递送给相应的进程/线程 以触发 默认动作/忽略动作/信号处理函数。

Demo:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define USRSIG SIGUSR1
#define RTSIG SIGRTMIN+8


void usrHandler(int signum,siginfo_t *info,void *ucontext)
{
  printf("%d , SIGUSR1 reveived \n",signum);
  printf("Sender pid[%d] , User cost time [%ld] , System cost time [%ld] , si_code [%d] \n ",
                  info->si_pid,info->si_utime,info->si_stime,info->si_code);

  sleep(15);
  printf("exit usrHandler\n");
}

void usrHandler2(int signum,siginfo_t *info,void *ucontext)
{
  printf("%d , SIGUSR2 received \n",signum);
}

int main(int argc,char** argv)
{
// set SIGUSR1
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask,SIGUSR2); // SIGUSR2 will be blocked when usrHandler is executing. After return from  usrHandler, SIGUSR2 will
                           // be received adn surHandler2 will be executed.
  struct sigaction act;
  memset(&act,0x0,sizeof(struct sigaction));
  struct sigaction oldact;
  memset(&oldact,0x0,sizeof(struct sigaction));

  act.sa_sigaction = usrHandler;
  act.sa_mask = mask;
  act.sa_flags = 0; //no flag is set

  sigaction(SIGUSR1, &act, &oldact);

// set SIGSUR2
  sigset_t mask2;
  sigemptyset(&mask2);

  struct sigaction act2;
  memset(&act2,0x0,sizeof(struct sigaction));
  struct sigaction oldact2;
  memset(&oldact2,0x0,sizeof(struct sigaction));

  act2.sa_sigaction = usrHandler2;
  act2.sa_mask = mask2;
  act2.sa_flags = 0; //no flag is set

  sigaction(SIGUSR2, &act2, &oldact2);



  while(1) {;}
}

当通过 kill 连续发送 SIGUSR1 和 SIGUSR2 给上面的例子时,会发现执行流程会卡在 SIGUSR1 处理函数的 sleep ,这是因为针对 SIGUSR1 设置了block SIGUSR2,这会导致 SIGUSR2 无法中断 SIGUSR1。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1153113.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

亚马逊美国站衣物收纳商品合规标准是什么?如何办理?

随着秋季的来临&#xff0c;不少人翻箱倒柜地寻找换季用品。相信现在很多人都和小编一样&#xff0c;出门时打算找个外套穿上&#xff0c;但想到要去柜子里翻半天&#xff0c;就立刻打消了想要出门的念头。 但当翻箱倒柜地找到了换季用品&#xff0c;却又要一件一件地把翻出来…

Variations-of-SFANet-for-Crowd-Counting可视化代码

前文对Variations-of-SFANet-for-Crowd-Counting做了一点基础梳理&#xff0c;链接如下&#xff1a;Variations-of-SFANet-for-Crowd-Counting记录-CSDN博客 本次对其中两个可视化代码进行梳理 1.Visualization_ShanghaiTech.ipynb 不太习惯用jupyter notebook, 这里改成了p…

spring解决后端显示时区的问题

spring解决后端显示时区的问题 出现的问题&#xff1a; 数据库中的数据&#xff1a; 解决方法 spring:jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: Asia/Shanghai

vscode前端必备插件

安装插件的位置如下&#xff1a; 1、Chinese (Simplified) Language Pack 中文简体插件 2、Vetur Vue官方钦定插件&#xff0c;包括&#xff1a;语法高亮&#xff0c;智能提示&#xff0c;错误提示&#xff0c;格式化&#xff0c;自动补全等等 3、ESLint 语法检查工具&#…

客户端性能测试基础知识

目录 1、客户端性能 1.1、客户端性能基础知识 2、客户端性能工具介绍与环境搭建 2.1.1、perfdog的使用 2.1.2、renderdoc的使用 1、客户端性能 1.1、客户端性能基础知识 客户端性能知识这里对2D和3D类游戏进行展开进行&#xff0c;讲述的有内存、CPU、GPU、帧率这几个模块…

云栖大会十五年:开放创新,未来愿景

时光荏苒&#xff0c;转眼间云栖大会已经走过了十五个年头&#xff0c;这一场中国云计算行业的盛会已经成为业内不可或缺的一部分。在这个特殊的时刻&#xff0c;我想分享一些对未来云栖大会的期待与建议&#xff0c;希望这个盛会能够继续推动云计算领域的创新和发展。 云栖大会…

数据库深入浅出,数据库介绍,SQL介绍,DDL、DML、DQL、TCL介绍

一、基础知识&#xff1a; 1.数据库基础知识 数据(Data)&#xff1a;文本信息(字母、数字、符号等)、音频、视频、图片等&#xff1b; 数据库(DataBase)&#xff1a;存储数据的仓库&#xff0c;本质文件&#xff0c;以文件的形式将数据保存到电脑磁盘中 数据库管理系统(DBMS)&…

LSF 概览——了解 LSF 是如何满足您的作业要求,并找到最佳资源来运行该作业的

LSF 概览 了解 LSF 是如何满足您的作业要求&#xff0c;并找到最佳资源来运行该作业的。 IBM Spectrum LSF ("LSF", load sharing facility 的简称) 软件是行业领先的企业级软件。LSF 将工作分散在现有的各种 IT 资源中&#xff0c;以创建共享的&#xff0c;可扩展…

国内内卷太严重,还不考虑一下在海外接单?那这几个平台你知道吗?

作为一个程序员&#xff0c;在平台上接单赚点外快是再正常不过的事情了&#xff0c;但是现今国内各个平台都内卷比较严重&#xff0c;你是否考虑过去“外面的世界”看看&#xff1f; 如果想过&#xff0c;那么这几个外国的接单平台你都知道吗&#xff1f; 接下来就和我一起来看…

vmWare虚拟机扩容及pip国内镜像源

扩展虚拟机容量 打开虚拟机.sudo apt-get install gparted pip镜像源 pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple-i https://pypi.douban.com/simple-i https:// mirrors.aliyun.com/pypi/simple

Linux CentOS7 shell

学好linux&#xff0c;首先要深入理解shell。 shell俗称壳&#xff0c;它包裹在内核的外面&#xff0c;是用户命令的翻译官。 作用&#xff1a;接收用户的命令&#xff0c;翻译后(处理一下)交给Linux内核处理。 用户执行命令 -> shell -> 内核 -> CPU -> 内核 -…

C/C++笔试易错与高频题型图解知识点(三)——数据结构部分(持续更新中)

目录 1. 排序 1.1 冒泡排序的改进 2. 二叉树 2.1 二叉树的性质 3. 栈 & 队列 3.1 循环队列 3.2 链式队列 4. 平衡二叉搜索树——AVL树、红黑树 5 优先级队列&#xff08;堆&#xff09; 1. 排序 1.1 冒泡排序的改进 下面的排序方法中&#xff0c;关键字比较次数与记录的初…

LeetCode 996.正方形数组的数目

和上一道状压的区别在于我们要去重一下~ 思路都是和上一篇博客是一样的&#xff0c;感兴趣的同学可以看一下 const int N 15; int dp[1<<N][N]; int n; vector<int>nums1;bool check(int x){int tem sqrt(x);if(tem*temx)return 1;return 0; }int dfs(int u,in…

比较Excel中的两列目录编号是否一致

使用java代码比较excel中两列是否有包含关系&#xff0c;若有包含关系&#xff0c;核对编号是否一致。 excel数据样例如下&#xff1a; package com.itownet.hg;import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;import j…

网站如何改成HTTPS访问

在今天的互联网环境中&#xff0c;将网站更改成HTTPS访问已经成为了一种标准做法。HTTPS不仅有助于提高网站的安全性&#xff0c;还可以提高搜索引擎排名&#xff0c;并增强用户信任。因此&#xff0c;转换为HTTPS是一个重要的举措&#xff0c;无论您拥有个人博客、电子商务网站…

如何将你的PC电脑数据迁移到Mac电脑?使用“迁移助理”从 PC 传输到 Mac的具体操作教程

有的小伙伴因为某一项工作或者其它原因由Windows电脑换成了Mac电脑&#xff0c;但是数据和文件都在原先的Windows电脑上&#xff0c;不知道怎么传输。接下来小编就为大家介绍使用“迁移助理”将你的通讯录、日历、电子邮件帐户等内容从 Windows PC 传输到 Mac 上的相应位置。 在…

PicoDiagnostics (NVH设备软件)-Mongoose识别不了VIN码

如果Mongoose J2534诊断线识别不到车辆的VIN码&#xff0c;通常在PD软件中会像下图那样提示。 遇到这种情况&#xff0c;首先确保你的电脑是否已经安装J2534驱动&#xff1a;打开【设备管理器】&#xff0c;如果你将示波器和Mongoose J2534诊断线连接到电脑&#xff0c;【设备管…

EtherCAT FP介绍系列文章—RAS

RAS扩展功能包是acontis公司在EC-Master EtherCAT主站基础上提供的一套基于TCP/IP的客户端/服务器架构的Remote API。Remote API旨在远程API提供了一个接口&#xff0c;解决在操作系统中当第二个进程&#xff08;例如OPC服务器&#xff09;可能访问EtherCAT总线的数据或在Ether…

oracle 校验左括号和有括号是否对称匹配

校验数据比如名称字段的左括号和有括号是否匹配。不匹配情况有&#xff1a; 左括号是英文的&#xff0c;右括号是中文的&#xff1b;右括号是中文的&#xff0c;左括号是英文的&#xff1b; 通过正则表达式对名称进行校验&#xff0c;校验脚本如下&#xff1a; SELECT NAMEFR…

超越YOLOv8?基于Gold YOLO的自定义数据集训练

Gold-YOLO的出色性能是对Noahs Ark Lab团队的奉献和专业知识的证明。它不仅超越了其前身YOLOv8&#xff0c;还为实时目标检测设定了新标准。凭借其闪电般快速的处理能力和出色的准确性&#xff0c;Gold-YOLO承诺革命化一系列应用&#xff0c;从自动驾驶车辆到监视系统等等。 我…