myalarm_王喜燕

main.c

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include "myalarm.h"
int main(void)
{
    sig_reg();
    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;
    
}

myalarm.c

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>
#include "myalarm.h"
void any1(void *s)
{
    printf("%s",(char *)s);
    fflush(NULL);
}

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

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

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);
    }
}
void sig_reg(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);
}

myalarm.h

#ifndef __MYALARM__H
#define __MYALARM__H

typedef void (*sig_func)(void *);
typedef struct
{
    int delay;
    sig_func handler;
    char *ptr;
}alarm_t;

static alarm_t *alarm_p[10];

void any1(void *s);
void any2(void *s);
void any3(void *s);
void alrm_handler(int s);
void sig_reg(void);
void anytimer_alarm(int delay,sig_func handler,char * ptr);

#endif

makefile

SRC=main.o myalarm.o
OBJ=myalarm

$(OBJ):$(SRC)
    gcc $^ -o $@ 
clean:
    rm -rf *.o $(OBJ)

 

posted @ 2019-03-24 14:41  q*r&s  阅读(187)  评论(0编辑  收藏  举报