关闭

Linux下alarm,sigaction,pause

185人阅读 评论(0) 收藏 举报
分类:
/*
  #include <unistd.h>
  unsigned int alarm(unsigned int seconds);

  RETURN VALUE
       alarm() returns the number of seconds remaining  until  any  previously
       scheduled alarm was due to be delivered, or zero if there was no previ‐
       ously scheduled alarm.

*/


/*
#include<stdio.h>
#include <unistd.h>

unsigned int ret=0;
unsigned seconds=10;
int main(void)
{
	while(1)
	{
	 ret=alarm(seconds);
     sleep(5);	 
	 printf("ret=%d.\n",ret);	
	}

	return 0;
}

//结果值是0,5,5,5循环5
*/

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

void func(int sig)
{
	if(sig==SIGALRM)
	{
		printf("alarm happened.\n");
	}
}

unsigned ret=-1;
struct sigaction act={0};

int main(void)
{
	
     act.sa_handler=func;
	 sigaction(SIGALRM,&act,NULL);
                     

	 ret=alarm(8);
	 sleep(1);
	 printf("1st,ret=%d.\n",ret);
	 
	 ret=alarm(5);
	 sleep(2);
	 printf("2st,ret=%d.\n",ret);
	 
	 ret=alarm(6);
	 sleep(3);
	 printf("3st,ret=%d.\n",ret);
	 
	 
	 pause();
	
	 return 0;
	
}

//结果为:1st,ret=0.
//        2st,ret=7.
//        3st,ret=3.
//        alarm happened
*/
//***************************************************************
/*
//sigaction+alarm模拟sleep
#include<stdio.h>
#include <signal.h>
#include <unistd.h>

void func(void)
{
	
}

void mysleep(unsigned int seconds)
{

	struct sigaction act={0};
	
	act.sa_handler= func;
	sigaction(SIGALRM,&act,NULL);
    
	alarm(seconds);
	pause();
}

int main(void)
{
	
	printf("before mysleep.\n");
	mysleep(5);
	printf("after mysleep.\n");
	
	return 0;
}

*/

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

2.sigaction

  #include <signal.h>
  int sigaction(int signum, const struct sigaction *act,
                     struct sigaction *oldact);

 The sigaction structure is defined as something like:
  struct sigaction {
               void     (*sa_handler)(int);
               void     (*sa_sigaction)(int, siginfo_t *, void *);
               sigset_t   sa_mask;
               int        sa_flags;
               void     (*sa_restorer)(void);
                             };






0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:26776次
    • 积分:876
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:86篇
    • 译文:0篇
    • 评论:0条
    雁过留影,人过留言
    望行业师哥,师姐,留下你们的宝贵建议,愿学弟学妹留下你们的疑惑,共同进步,赢在共赢!