代码改变世界

2019.3.23作业

2019-03-23 20:16  叶子悠悠  阅读(164)  评论(0编辑  收藏  举报
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<unistd.h>
#include<sys/time.h>

#define BUFSIZE 512
#define TK_MAX 1024
int anyam(void);
static void am_handler2(int s);
typedef struct myalrm_st{
	int sec;
	char buf[BUFSIZE];	
	void (*myf)(int s);
}myalrm_t;
static myalrm_t *tk[TK_MAX] = {};
int any_alrm(int s,char *str,void (*myfunk)(int s))
{
	myalrm_t *am = NULL;	
	am = malloc(sizeof(*am));	
	if(am == NULL)
		return -1;
//	printf("1111\n");
	am->sec = s;
	strcpy(am->buf,str);
	am->myf = myfunk;
//	printf("%d\n",am->sec);
	for(int i = 0;i < TK_MAX;i++)
	{
		if(tk[i] == NULL)
		{
			tk[i] = am;
			//printf(" %d",i);
			break;
		}
	}
//	printf("2222\n");
	anyam();
	//printf("9\n");
	return 1;
}

int anyam(void)
{
//	printf("3333\n");
	int i;
	struct sigaction act;
	struct itimerval new;
	new.it_value.tv_sec = 1;
	new.it_value.tv_usec = 0;
	new.it_interval.tv_sec = 1;
	new.it_interval.tv_usec = 0;
	setitimer(ITIMER_REAL,&new,NULL);
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	for(i = 0;i < TK_MAX;i++)
	{
		//printf("&&&\n");
		if(tk[i] != NULL)
		{
			act.sa_handler = am_handler2;
		//	printf("%d\n",tk[i]->sec);
		}
	}
	sigaction(SIGALRM,&act,NULL);
		//printf("666\n");
		//if(tk[i] == NULL)
		//	break;
	return 1;
}
static void am_handler2(int s)
{
	int i;
	for(i = 0;i < TK_MAX;i++)
	{
		if(tk[i] != NULL)
		{
			if(tk[i]->sec != 0)
			{
				tk[i]->sec -= 1;
			}
			else
			{
				tk[i]->myf(i);
				tk[i] = NULL;
				break;
			}
		}
	}
}
static void am_handler(int s)
{
	printf("qwer");
	fflush(NULL);
}
static void am_handler3(int s)
{
	printf("aslal");
	fflush(NULL);
}
static void am_handler4(int s)
{
	printf("apue");
	fflush(NULL);
}
int main(void)
{
	any_alrm(15,"aslal",am_handler3);
	any_alrm(5,"qwer",am_handler);
	any_alrm(10,"apue",am_handler4);
	while(1)
	{
		write(1,"*",1);
		sleep(1);
	}

	exit(0);
}