其他分享
首页 > 其他分享> > 实现终端打印 **world*hello**apue*******

实现终端打印 **world*hello**apue*******

作者:互联网

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>

typedef void (*sig_func)(void *);
typedef struct
{
    int delay;
    sig_func handler;
    char *ptr;
}alarm_t;
static alarm_t *alarm_p[10];
void anytimer_alarm(int delay,sig_func handler,char * ptr);
static void any1(void *s)
{
    printf("%s",(char *)s);
    fflush(NULL);
}

static void any2(void *s)
{
    printf("%s",(char *)s);
    fflush(NULL);
}

static void any3(void *s)
{
    printf("%s",(char *)s);
    fflush(NULL);
}
/*
    信号到来对结构体中的数据进行操作
*/
static void alrm_handler(int s)
{
    for(int i = 0; i < 10; i++)
    {
        if(alarm_p[i] != NULL)
        {
            alarm_p[i]->delay -= 1;
            if(alarm_p[i]->delay == 0)
            {
                alarm_p[i]->handler(alarm_p[i]->ptr);
            }
        }
    }
}
/*
    把参数存到结构体里,将结构体的地址存到指针数组中
*/
void anytimer_alarm(int sec,sig_func handler,char * ptr)
{
    int i = 0;
    alarm_t *at = NULL;
    at = malloc(sizeof(alarm_t));
    if(at == NULL)
    {
        fprintf(stderr,"malloc():%s\n",strerror(errno));
        exit(1);
    }
    at->delay = sec;
    at->handler = handler;
    at->ptr = ptr;
    for( i;i < 10;i++)
    {
        if(alarm_p[i] == NULL)
        {
            alarm_p[i] = at;
            break;
        }
    }
    if(i == 10)
    {
        free(at);
        exit(1);
    }
}
int main(void)
{
    struct itimerval itv;
    struct sigaction act;
    //注册信号行为
    act.sa_handler = alrm_handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGALRM,&act,NULL);
    //注册信号间隔几秒发送一次
    itv.it_interval.tv_sec = 1;
    itv.it_interval.tv_usec = 0;
    itv.it_value.tv_sec = 1;
    itv.it_value.tv_usec = 0;
    setitimer(ITIMER_REAL,&itv,NULL);

    anytimer_alarm(3,any1,"hello");
    anytimer_alarm(2,any2,"world");
    anytimer_alarm(5,any3,"apue");
    /*
    **world*hello*apue******
    */
    while(1)
    {
        write(1,"*",1);
        sleep(1);
    }
    return 0;    
}

 

标签:include,apue,int,alarm,hello,handler,world,NULL,void
来源: https://www.cnblogs.com/Mr-zzzzzz/p/10587253.html