3.23 多任务计时器

alrm.h:

#ifndef __ALRM_H #define __ALRM_H typedef void(*any_t)(void *); int anytimer_alarm(int sec, any_t any, void *a); #endif
alrm.c:

#include "alrm.h" #include <sys/time.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <signal.h> static int flag; typedef struct { int sec; any_t any; char *arg; }tim_t; #define MAX 1024 tim_t *at[MAX]; int get_pos(void) { for(int i = 0; i < MAX; i++) { if(at[i] == NULL) { return i; } } } void handler(int s)
{
    for(int i=0; i < MAX; i++) {
        if(at[i] != NULL) {
            if(at[i]->sec != 0) {
                at[i]->sec -= 1;
                if(at[i]->sec == 0) {
                    (at[i]->any)(at[i]->arg);
                }
            }
        }
    }
}

void load(void)
{
    struct sigaction act, oldact;
    struct itimerval tim, oldtim;
    act.sa_handler = handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGALRM, &act, &oldact);

    tim.it_interval.tv_sec = 1;
    tim.it_interval.tv_usec = 0;
    tim.it_value.tv_sec = 1;
    tim.it_value.tv_usec = 0;
    setitimer(ITIMER_REAL, &tim, &oldtim);
}

int anytimer_alarm(int sec, any_t any, void *a)
{
    int id;
    tim_t *tim = NULL;
    tim = malloc(sizeof(*tim));
    if(tim == NULL) {
        return -1;
    }
    if(flag == 0) {
        load();
        flag = 1;
    }
    tim->sec = sec;
    tim->any = any;
    tim->arg = malloc(strlen((char *)a));
    if(tim->arg == NULL) {
        free(tim);
        return -1;
    }
    strcpy(tim->arg, (char *)a);
    id = get_pos();
    at[id] = tim;
    return id;
}
主函数:

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

猜你喜欢

转载自www.cnblogs.com/chenbin123/p/10585060.html