28.semaphore跨进程通信
- 根据id创建Semaphore,并初始化有一个信号量可用 name类型是char *...;
1 HANDLE hsem = CreateSemaphoreA(NULL, 1, 1, name);
- 关闭句柄
1 CloseHandle(hsem);
- 根据id打开semaphore
1 HANDLE hsem = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, TRUE, name);
- 接受Semaphore句柄
1 DWORD res = WaitForSingleObject(hsem, 20000);
- 检测是否收到
1 switch (res) 2 { 3 case WAIT_OBJECT_0: 4 printf("收到信号-------"); 5 break; 6 case WAIT_TIMEOUT: 7 printf("超时没有收到-------"); 8 break; 9 case WAIT_ABANDONED: 10 printf("另外一个进程意外终止-------"); 11 break; 12 default: 13 break; 14 15 }
完整代码:
主信号.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 5 char name[100] = "haihualovefang"; 6 7 void main() 8 { 9 HANDLE hsem = CreateSemaphoreA(NULL, 0, 1, name); 10 printf("创建成功"); 11 char ch = getch(); 12 13 14 ReleaseSemaphore(hsem, 1, NULL); 15 printf("触发信号量"); 16 CloseHandle(hsem); 17 18 19 }
wait.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 5 char name[100] = "haihualovefang"; 6 7 void main() 8 { 9 10 HANDLE hsem = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, TRUE, name);; 11 if (hsem == NULL) 12 { 13 printf("打开失败"); 14 system("pause"); 15 return; 16 } 17 printf("等待-------"); 18 DWORD res = WaitForSingleObject(hsem, 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(hsem); 35 36 37 38 system("pause"); 39 }