Advertisement
3axap_010

WaitForEvent.cpp

Mar 18th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <windows.h>
  2. #include <stdio.h>
  3.  
  4. int main(int argc, char** argv)
  5. {
  6.     if (argc < 2)
  7.     {
  8.         fprintf(stderr, "Incorrect process start\n");
  9.         return 1;
  10.     }
  11.  
  12.     HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, argv[1]);
  13.     if (hEvent == NULL)
  14.     {
  15.         fprintf(stderr, "Can't open event, error: %d\n", GetLastError());
  16.         system("pause");
  17.         return 1;
  18.     }
  19.  
  20.     HANDLE hSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, "Semaphore");
  21.     if (!hSemaphore)
  22.     {
  23.         fprintf(stderr, "Can't open a semaphore, error: %d", GetLastError());
  24.         CloseHandle(hEvent);
  25.         return 1;
  26.     }
  27.  
  28.     HANDLE hHandles[2] = { hEvent, hSemaphore };
  29.     int running = 1;
  30.  
  31.     while (running)
  32.     {
  33.         DWORD dWaitResult = WaitForMultipleObjects(2, hHandles, FALSE, INFINITE);
  34.         switch (dWaitResult)
  35.         {
  36.         case WAIT_OBJECT_0:
  37.             ResetEvent(hEvent);
  38.             running = 0;
  39.             break;
  40.         case WAIT_OBJECT_0 + 1:
  41.             fprintf(stdout, "%s\n", argv[1]);
  42.             ReleaseSemaphore(hSemaphore, 1, NULL);
  43.             break;
  44.         default:
  45.             fprintf(stderr, "Waiting error: %d\n", GetLastError());
  46.             running = 0;
  47.             break;
  48.         }
  49.     }
  50.  
  51.     CloseHandle(hEvent);
  52.     CloseHandle(hSemaphore);
  53.  
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement