进程、线程---------信号

信号机制

​信号是在软件层次上对中断机制的一种模拟,是一种异步通信方式linux内核通过信号通知用户进程,不同的信号类型代表不同的事件Linux对早期的unix信号机制进行了扩展                                    进程对信号有不同的响应方式

缺省方式

忽略信号

捕捉信号

信号的产生

​按键产生

系统调用函数产生(比如raise, kill)

硬件异常

命令行产生 (kill)

软件条件 (比如被0除,访问非法内存)等

​信号相关命令

​kill  [signal] pid

发送信号kill/raise

发送信号kill/raise

​定时器函数:

int​ alaem(unsigned int seconds);

​ualarm 循环发送

信号的发送:

int杀死 (pid_tpid,intsignum)
功能:发送信号
参数:
pid:>0发送信号给指定进程
=0:发送信号给跟调用杀函数的那个进程处于同一进程组的进程。
<-1: 取绝对值,发送信号给该绝对值所对应的进程组的所有组员
=-1:发送信号给,有权限发送的所有进程。
信号:待发送的信号
#include <sys/types.h>
#include <signal.h>

int main(){

  raise(11);
  alarm(3);
}

​信号捕捉

signal 函数:捕捉信号执行自定义函数

​sigaction函数

信号捕捉1:

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

typedef void (*sighandler_t)(int);
sighandler_t  oldact;

void handle(int sig)
{
   printf("i can the sigint");
    signal(SIGINT,oldact);
}
int main(){
 oldact = signal(SIGINT,handle);
   while(1)
{
   sleep(1);
 }
}

​信号捕捉2:

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

typedef void (*sighandler_t)(int);
sighandler_t  oldact;
void handle(int sig){
   if(sig == SIGINT){
   printf("i  cath  the sigint \n")
  else if (sig == SIGALRM){
   printf("second timer \n");
    //alarm(1);
    }; 
 }
}

void handle(int sig)
{
   printf("i can the sigint");
    signal(SIGINT,oldact);
}
int main(){
   struct sigaction act;
   act.sa_handler = handle;
   act.sa_flags = 0;
   sigemptyset(act.sa_mask);
   sigaction(SIGINT,&act,NULL);        //捕捉int信号
   sigation(SIGALRM,&act,NULL);      //捕捉定时器信号
  
   struct itimerval timevalue;
   timevalue.it_interval.tv_sec = 1;
   timevalue.it_interval.tv_usec = 0;
   timevalue.it_value.tv_sec = 5;
   timevalue.it_value.tv_usec = 0;
  
   setitimer(ITIMER_REAL, &timevalue,NULL); 
   sigaction(SIGALRM,&act,NULL);
  while(1)
{
     // sleep(1);
 }
}

信号集、信号的阻塞

​有时候不希望在接到信号时就立即停止当前执行,去处理信号,同时也不希望忽略该信号,而是延时一段时间去调用信号处理函数。这种情况可以通过阻塞信号实现

​int pause(void)

​进程一直阻塞,直到被信号中断,返回值: -1 并设置 errno 为 EINTR函数行为:

1 如果信号的默认处理动作是终止进程,则进程终止,pause 函数么有机会返回                              2 如果信号的默认处理动作是忽略,进程继续处于挂起状态,pause 函数不返回、五号A A a          3 如果信号的处理动作是捕捉,则调用完信号处理函XBi                                                                  4 pause 收到的信号如果被屏蔽,那么 pause 就不能被唤醒

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

 void handle(int sig){
  printf(" i get sig  = %d\n",sig);
}


int main()
{  struct sigacth act;
   act.sa_handler = handle;
   act.sa_flags = 0;
   sigemptyset(&act.sa_mask);
   sigaction(SIGINT,&act,NULL);


  pause();

 printf("after pause\n");}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值