linux中的信号3——alarm、pause函数

来源:互联网 发布:六级分数算法 编辑:程序博客网 时间:2024/06/03 17:19
以下内容源于朱有鹏《物联网大讲堂》课程的学习,如有侵权,请告知删除。

1、alarm函数



  • 内核以API形式提供的闹钟;
  • 可以为当前进程定义闹钟,时间到了会发出SIGALRM信号。
  • 每个进程只能有一个alarm,当重新定义时,会重新计时。
  • 注意函数的返回值,见上图文字。

ret = alarm(5);printf("1st, ret = %d.\n", ret);sleep(3);ret = alarm(5);// 返回值是2但是本次alarm会重新定5sprintf("2st, ret = %d.\n", ret);sleep(1);ret = alarm(5);         //返回值时4,但是本次的alarm会重新定5sprintf("3st, ret = %d.\n", ret);

2、pause函数

  • pause函数的作用,是让当前进程暂停运行,交出CPU给其他进程去执行
  • 当前进程进入pause状态后,当前进程会表现为“卡住、阻塞住”;
  • 要退出pause状态,当前进程需要被信号唤醒。



3、使用alarm和pause来模拟sleep

#include <stdio.h>#include <unistd.h> // unix standand#include <signal.h>void func(int sig){/*if (sig == SIGALRM){printf("alarm happened.\n");}*/}void mysleep(unsigned int seconds);int main(void){printf("before mysleep.\n");mysleep(3);printf("after mysleep.\n");/*unsigned int ret = -1;struct sigaction act = {0};act.sa_handler = func;sigaction(SIGALRM, &act, NULL);//signal(SIGALRM, func);ret = alarm(5);printf("1st, ret = %d.\n", ret);sleep(3);ret = alarm(5);// 返回值是2但是本次alarm会重新定5sprintf("2st, ret = %d.\n", ret);sleep(1);ret = alarm(5);         //返回值时4,但是本次的alarm会重新定5sprintf("3st, ret = %d.\n", ret);//while (1);pause();*/return 0;}void mysleep(unsigned int seconds){struct sigaction act = {0};//act.sa_handler = func;//sigaction(SIGALRM, &act, NULL);//这三行应该能省略吧?alarm(seconds);pause();}


阅读全文
0 1
原创粉丝点击