Mysoft

Untitled

Nov 22nd, 2026
31
0
0 sec
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 7.28 KB | None | 0 0
  1. #define WIN32_LEAN_AND_MEAN
  2. #include <windows.h>
  3. #include <process.h>
  4. #include <stdarg.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7.  
  8. #define SLOT_NAME    "\\\\.\\mailslot\\c_overlapped_demo"
  9. #define MAX_MSG_SIZE 4096
  10.  
  11. typedef struct {
  12.     HANDLE           hReadyEvent;
  13.     HANDLE           hStopEvent;
  14.     CRITICAL_SECTION printCs;
  15. } AppContext;
  16.  
  17. static void SafePrint(AppContext *ctx, const char *fmt, ...) {
  18.     va_list args;
  19.     EnterCriticalSection(&ctx->printCs);
  20.     va_start(args, fmt);
  21.     vprintf(fmt, args);
  22.     va_end(args);
  23.     putchar('\n');
  24.     fflush(stdout);
  25.     LeaveCriticalSection(&ctx->printCs);
  26. }
  27.  
  28. static unsigned __stdcall ServerThread(void *userdata) {
  29.     AppContext *ctx = (AppContext *)userdata;
  30.     HANDLE hSlot;
  31.     HANDLE hReadEvent;
  32.     HANDLE waitHandles[2];
  33.     char buffer[MAX_MSG_SIZE];
  34.     OVERLAPPED ov;
  35.     DWORD bytesRead;
  36.  
  37.     /* CreateMailslot inherently creates an asynchronous (overlapped) handle */
  38.     hSlot = CreateMailslotA(
  39.         SLOT_NAME,
  40.         MAX_MSG_SIZE,
  41.         MAILSLOT_WAIT_FOREVER,
  42.         NULL
  43.     );
  44.  
  45.     if (hSlot == INVALID_HANDLE_VALUE) {
  46.         SafePrint(ctx, "[Server] CreateMailslot failed. Error: %lu", GetLastError());
  47.         SetEvent(ctx->hReadyEvent);
  48.         return 1;
  49.     }
  50.  
  51.     hReadEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
  52.     if (hReadEvent == NULL) {
  53.         SafePrint(ctx, "[Server] CreateEvent failed. Error: %lu", GetLastError());
  54.         CloseHandle(hSlot);
  55.         SetEvent(ctx->hReadyEvent);
  56.         return 1;
  57.     }
  58.  
  59.     SafePrint(ctx, "[Server] Listening on %s", SLOT_NAME);
  60.     SetEvent(ctx->hReadyEvent);
  61.  
  62.     waitHandles[0] = hReadEvent;
  63.     waitHandles[1] = ctx->hStopEvent;
  64.  
  65.     for (;;) {
  66.         ZeroMemory(&ov, sizeof(OVERLAPPED));
  67.         ResetEvent(hReadEvent);
  68.         ov.hEvent = hReadEvent;
  69.         bytesRead = 0;
  70.  
  71.         BOOL ok = ReadFile(
  72.             hSlot,
  73.             buffer,
  74.             MAX_MSG_SIZE,
  75.             NULL,
  76.             &ov
  77.         );
  78.  
  79.         if (!ok) {
  80.             DWORD errCode = GetLastError();
  81.             if (errCode == ERROR_IO_PENDING) {
  82.                 /* Wait for either an incoming message or the shutdown event */
  83.                 DWORD waitRes = WaitForMultipleObjects(
  84.                     2,
  85.                     waitHandles,
  86.                     FALSE,
  87.                     INFINITE
  88.                 );
  89.  
  90.                 if (waitRes == WAIT_OBJECT_0) {
  91.                     if (!GetOverlappedResult(hSlot, &ov, &bytesRead, FALSE)) {
  92.                         SafePrint(ctx, "[Server] GetOverlappedResult failed. Error: %lu", GetLastError());
  93.                         break;
  94.                     }
  95.                 } else if (waitRes == (WAIT_OBJECT_0 + 1)) {
  96.                     /* Cancel the pending IRP cleanly before ov and buffer leave scope */
  97.                     CancelIo(hSlot);
  98.                     GetOverlappedResult(hSlot, &ov, &bytesRead, TRUE);
  99.                     SafePrint(ctx, "[Server] Shutdown signal received.");
  100.                     break;
  101.                 } else {
  102.                     SafePrint(ctx, "[Server] WaitForMultipleObjects failed. Error: %lu", GetLastError());
  103.                     break;
  104.                 }
  105.             } else {
  106.                 SafePrint(ctx, "[Server] ReadFile failed. Error: %lu", errCode);
  107.                 break;
  108.             }
  109.         } else {
  110.             /* Completed synchronously during ReadFile */
  111.             if (!GetOverlappedResult(hSlot, &ov, &bytesRead, FALSE)) {
  112.                 SafePrint(ctx, "[Server] GetOverlappedResult (sync) failed. Error: %lu", GetLastError());
  113.                 break;
  114.             }
  115.         }
  116.  
  117.         if (bytesRead > 0) {
  118.             SafePrint(ctx, "[Server] Received (%lu bytes): %.*s", bytesRead, (int)bytesRead, buffer);
  119.         }
  120.     }
  121.  
  122.     CloseHandle(hReadEvent);
  123.     CloseHandle(hSlot);
  124.     SafePrint(ctx, "[Server] Stopped.");
  125.     return 0;
  126. }
  127.  
  128. static unsigned __stdcall ClientThread(void *userdata) {
  129.     AppContext *ctx = (AppContext *)userdata;
  130.     HANDLE hFile;
  131.     HANDLE hWriteEvent;
  132.     OVERLAPPED ov;
  133.     DWORD bytesWritten;
  134.     char payload[256];
  135.  
  136.     /* Ensure the server has created the mailslot before opening it */
  137.     WaitForSingleObject(ctx->hReadyEvent, INFINITE);
  138.  
  139.     /* FILE_SHARE_READ is required for mailslot clients; FILE_FLAG_OVERLAPPED enables async I/O */
  140.     hFile = CreateFileA(
  141.         SLOT_NAME,
  142.         GENERIC_WRITE,
  143.         FILE_SHARE_READ,
  144.         NULL,
  145.         OPEN_EXISTING,
  146.         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  147.         NULL
  148.     );
  149.  
  150.     if (hFile == INVALID_HANDLE_VALUE) {
  151.         SafePrint(ctx, "[Client] CreateFile failed. Error: %lu", GetLastError());
  152.         return 1;
  153.     }
  154.  
  155.     hWriteEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
  156.     if (hWriteEvent == NULL) {
  157.         SafePrint(ctx, "[Client] CreateEvent failed. Error: %lu", GetLastError());
  158.         CloseHandle(hFile);
  159.         return 1;
  160.     }
  161.  
  162.     for (int i = 1; i <= 5; ++i) {
  163.         int len = snprintf(payload, sizeof(payload), "Message #%d via overlapped mailslot I/O", i);
  164.         if (len < 0) {
  165.             break;
  166.         }
  167.  
  168.         ZeroMemory(&ov, sizeof(OVERLAPPED));
  169.         ResetEvent(hWriteEvent);
  170.         ov.hEvent = hWriteEvent;
  171.         bytesWritten = 0;
  172.  
  173.         BOOL ok = WriteFile(
  174.             hFile,
  175.             payload,
  176.             (DWORD)len,
  177.             NULL,
  178.             &ov
  179.         );
  180.  
  181.         if (!ok) {
  182.             DWORD errCode = GetLastError();
  183.             if (errCode == ERROR_IO_PENDING) {
  184.                 WaitForSingleObject(hWriteEvent, INFINITE);
  185.                 if (!GetOverlappedResult(hFile, &ov, &bytesWritten, FALSE)) {
  186.                     SafePrint(ctx, "[Client] GetOverlappedResult failed. Error: %lu", GetLastError());
  187.                     break;
  188.                 }
  189.             } else {
  190.                 SafePrint(ctx, "[Client] WriteFile failed. Error: %lu", errCode);
  191.                 break;
  192.             }
  193.         } else {
  194.             /* Completed synchronously during WriteFile */
  195.             if (!GetOverlappedResult(hFile, &ov, &bytesWritten, FALSE)) {
  196.                 SafePrint(ctx, "[Client] GetOverlappedResult (sync) failed. Error: %lu", GetLastError());
  197.                 break;
  198.             }
  199.         }
  200.  
  201.         SafePrint(ctx, "[Client] Sent (%lu bytes): %s", bytesWritten, payload);
  202.         Sleep(250);
  203.     }
  204.  
  205.     CloseHandle(hWriteEvent);
  206.     CloseHandle(hFile);
  207.     SafePrint(ctx, "[Client] Finished.");
  208.     return 0;
  209. }
  210.  
  211. int main(void) {
  212.     AppContext ctx;
  213.     HANDLE hSrvThread;
  214.     HANDLE hCliThread;
  215.  
  216.     ctx.hReadyEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
  217.     ctx.hStopEvent  = CreateEventA(NULL, TRUE, FALSE, NULL);
  218.     InitializeCriticalSection(&ctx.printCs);
  219.  
  220.     hSrvThread = (HANDLE)_beginthreadex(NULL, 0, ServerThread, &ctx, 0, NULL);
  221.     hCliThread = (HANDLE)_beginthreadex(NULL, 0, ClientThread, &ctx, 0, NULL);
  222.  
  223.     WaitForSingleObject(hCliThread, INFINITE);
  224.  
  225.     /* Allow the server to drain the final message, then interrupt its pending ReadFile */
  226.     Sleep(200);
  227.     SetEvent(ctx.hStopEvent);
  228.     WaitForSingleObject(hSrvThread, INFINITE);
  229.  
  230.     CloseHandle(hCliThread);
  231.     CloseHandle(hSrvThread);
  232.     CloseHandle(ctx.hReadyEvent);
  233.     CloseHandle(ctx.hStopEvent);
  234.     DeleteCriticalSection(&ctx.printCs);
  235.  
  236.     return 0;
  237. }
Advertisement
Add Comment
Please, Sign In to add comment