00001 #include <stdio.h> 00002 #include <stdlib.h> 00003 #include <sys/types.h> 00004 #include <sys/ipc.h> 00005 #include <sys/msg.h> 00006 00007 #include "hevent.h" 00008 00009 00011 struct hevent { 00012 int msqid; 00013 int blocking; 00014 }; 00015 00016 00017 struct hevent_msg { 00018 long mtype; 00019 int mtext; 00020 }; 00021 00022 00023 struct hevent* hevent_create(int blocking) 00024 { 00025 if (blocking > 1 || blocking < 0) 00026 return NULL; 00027 00028 struct hevent* event = calloc(1, sizeof(struct hevent)); 00029 event->msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT | IPC_EXCL); 00030 event->blocking = blocking; 00031 00032 if (event->msqid == -1) 00033 return NULL; 00034 00035 return event; 00036 } 00037 00038 00039 int hevent_notify(struct hevent* event, int notification) 00040 { 00041 if (event == NULL) 00042 return -1; 00043 00044 struct hevent_msg msg; 00045 msg.mtype = 1; 00046 msg.mtext = notification; 00047 if (msgsnd(event->msqid, &msg, sizeof(msg.mtext), 0) == -1) 00048 return -1; 00049 00050 return 0; 00051 } 00052 00053 00054 int hevent_wait(struct hevent* event) 00055 { 00056 if (event == NULL) 00057 return -1; 00058 00059 struct hevent_msg msg; 00060 00061 int msgflg = IPC_NOWAIT; 00062 if (event->blocking) 00063 msgflg = 0; 00064 00065 if (msgrcv(event->msqid, &msg, sizeof(msg.mtext), 0, msgflg) == -1) 00066 return -1; 00067 00068 return msg.mtext; 00069 } 00070 00071 00072 int hevent_remove(struct hevent* event) 00073 { 00074 if (event == NULL) 00075 return -1; 00076 00077 if (msgctl(event->msqid, IPC_RMID, NULL) == -1) 00078 return -1; 00079 else 00080 return 0; 00081 } 00082 00083