- 以id创建事件
1 char name[100] = "myevent"; 2 HANDLE event = CreateEventA(NULL, FALSE, FALSE, name);
- 设置事件
1 SetEvent(event);
- 关闭事件
1 CloseHandle(event);
- 另一个进程打开事件
1 HANDLE event = OpenEventA(EVENT_ALL_ACCESS, TRUE, name);//打开事件
- 然后等待事件
1 DWORD res = WaitForSingleObject(event, 20000);
- 等待结果
1 case WAIT_OBJECT_0: 2 printf("收到信号-------"); 3 break; 4 case WAIT_TIMEOUT: 5 printf("超时没有收到-------"); 6 break; 7 case WAIT_ABANDONED: 8 printf("另外一个进程意外终止-------"); 9 break;
完整代码:
event.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 5 char name[100] = "myevent"; 6 //mutex可以感知丢失,event无法感知 7 void main() 8 { 9 HANDLE event = CreateEventA(NULL, FALSE, FALSE, name); 10 printf("创建成功"); 11 char ch = getch(); 12 13 SetEvent(event); 14 printf("触发event"); 15 CloseHandle(event); 16 17 system("pause"); 18 }
wait.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 5 char name[100] = "myevent"; 6 7 void main() 8 { 9 HANDLE event = OpenEventA(EVENT_ALL_ACCESS, TRUE, name);//打开事件 10 11 if (event == NULL) 12 { 13 printf("打开失败"); 14 system("pause"); 15 return; 16 } 17 printf("等待-------"); 18 DWORD res = WaitForSingleObject(event, 20000); 19 switch (res) 20 { 21 case WAIT_OBJECT_0: 22 printf("收到信号-------"); 23 break; 24 case WAIT_TIMEOUT: 25 printf("超时没有收到-------"); 26 break; 27 case WAIT_ABANDONED: 28 printf("另外一个进程意外终止-------"); 29 break; 30 default: 31 break; 32 33 } 34 CloseHandle(event); 35 36 37 38 39 system("pause"); 40 }