Linux下alarm,sigaction,pause

/*
  #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);
                             };






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值