linux-C信号处理函数

本文展示了一个使用C语言处理信号的示例程序,其中包括如何捕捉SIGINT和SIGALRM信号,并通过设置信号回调函数来实现对这些信号的响应。程序演示了用户在限定时间内输入整数的过程,同时处理ctrl+c中断请求以及超时情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

void catch_int(int sig_num){
  signal(SIGINT,catch_int);//再次设置信号回调函数。ctrl+c:INT信号,ctrl+Z:挂起,TSTP信号.ctrl+\:发送BRT信号,进程立即中止,类似于ctrl-c,但灵活性更强
  printf("ctrl+c press!\n"); //ctrl+c失去作用,在此仅打印
  fflush(stdout); 
}
//深未来技术 http://deepfuture.iteye.com
void catch_alarm(int sig_num){
   printf("timeout,bye!\n");
   alarm(0);//清除定时器
   exit(0);
}
int main(void){
  int x; 
  signal(SIGALRM,catch_alarm);  //定时器信号
  signal(SIGINT,catch_int); //设置ctrl-c信号的回调函数是catch_int,以拦截ctrl-c。
  printf("please input an integer:");
  fflush(stdout); 
  alarm(20);//20秒时限
  scanf("%d",&x);//20秒内用户输入一个数
  printf("integer is :%d\n",x);
  return 0;
}

 knoppix@Microknoppix:/mnt-system/deepfuture$ gcc -o test9 test9.c
test9.c: In function 'catch_alarm':
test9.c:14: warning: incompatible implicit declaration of built-in function 'exit'

knoppix@Microknoppix:/mnt-system/deepfuture$ ./test9
please input an integer:^Cctrl+c press!
^Cctrl+c press!
^Cctrl+c press!
^Cctrl+c press!
timeout,bye!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值