您的位置:首页 > 运维架构 > Linux

Linux下alarm,sigaction,pause

2016-08-29 11:33 316 查看
/*
#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>
4000

#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);

                             };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐