进程1:创建信号量
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hSemaphore;
hSemaphore = CreateSemaphoreA(
NULL,
1,
1,
"Global\\aaa"
);
if (hSemaphore == NULL) {
printf("CreateSemaphoreA failed (%d)\n",GetLastError());
return 1;
}
printf("Semaphore created successfully.\n");
getchar();
CloseHandle(hSemaphore);
return 0;
}
进程2:打开信号量
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hSemaphore;
hSemaphore = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS,FALSE,"Global\\aaa");
if (hSemaphore == NULL) {
printf("OpenSemaphoreA failed (%d)\n",GetLastError());
return 1;
}
DWORD dwWaitResult = WaitForSingleObject(hSemaphore,0);
switch(dwWaitResult) {
case WAIT_OBJECT_0:
printf("Semaphore acquired successfully.\n");
break;
case WAIT_TIMEOUT:
printf("Semaphore not available,timeout.\n");
break;
default:
printf("WaitForSingleObject failed (%d)\n",GetLastError());
break;
}
CloseHandle(hSemaphore);
return 0;
}