Chris_M_Thomasson

Simple IOCP Write... ;^)

Apr 30th, 2017
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #define WIN32_LEAN_AND_MEAN
  2. #include <windows.h>
  3. #include <iostream>
  4. #include <cassert>
  5.  
  6.  
  7. // stupid crude auto close handle ;^)
  8. struct ct_win_hclose
  9. {
  10.     HANDLE m_h;
  11.  
  12.     ct_win_hclose(HANDLE h) : m_h(h) {
  13.         if (! m_h) throw;
  14.     }
  15.  
  16.     ~ct_win_hclose() {
  17.         if (! CloseHandle(m_h))
  18.         {
  19.             throw; // this is not good!
  20.         }
  21.     }
  22.  
  23.     // quick and dirty ;^o
  24.     operator HANDLE() { assert(m_h); return m_h; }
  25. };
  26.  
  27.  
  28. // Simple IOCP write.
  29. void test()
  30. {
  31.     // Create the iocp
  32.     ct_win_hclose iocp(CreateIoCompletionPort(
  33.         INVALID_HANDLE_VALUE,
  34.         NULL,
  35.         0,
  36.         0
  37.     ));
  38.     std::cout << "iocp: " << iocp << "\n";
  39.  
  40.     // Create testfile.bin
  41.     ct_win_hclose file(CreateFile(
  42.         TEXT("testfile.bin"),
  43.         GENERIC_READ | GENERIC_WRITE,
  44.         0,
  45.         NULL,
  46.         CREATE_ALWAYS,
  47.         FILE_FLAG_OVERLAPPED,
  48.         NULL
  49.     ));
  50.     std::cout << "file: " << file << "\n";
  51.  
  52.     // link file to iocp
  53.     if (CreateIoCompletionPort(
  54.         file,
  55.         iocp,
  56.         0,
  57.         0) != iocp)
  58.     {
  59.         throw;
  60.     }
  61.  
  62.     // Perform the initial write.
  63.     OVERLAPPED ol_origin;
  64.     ZeroMemory(&ol_origin, sizeof(ol_origin));
  65.     char buf[] = "Hello World";
  66.  
  67.     if (! WriteFile(
  68.         file,
  69.         buf,
  70.         sizeof(buf) - 1,
  71.         NULL,
  72.         &ol_origin))
  73.     {
  74.         DWORD lerr = GetLastError();
  75.         if (lerr != ERROR_IO_PENDING) throw;
  76.     }
  77.  
  78.     // Dequeue the write...
  79.     LPOVERLAPPED ol_dequeue = NULL;
  80.     ULONG_PTR key = 0;
  81.     DWORD bytes = 0;
  82.  
  83.     if (! GetQueuedCompletionStatus(
  84.         iocp,
  85.         &bytes,
  86.         &key,
  87.         &ol_dequeue,
  88.         INFINITE))
  89.     {
  90.         throw;
  91.     }
  92.  
  93.     assert(key == 0);
  94.  
  95.     std::cout << "write complete:" << bytes << " bytes\n";
  96. }
  97.  
  98.  
  99.  
  100. int main()
  101. {
  102.     test();
  103.  
  104.     std::cout << "\n\nComplete, hit <ENTER> to exit!\n";
  105.     std::fflush(stdout);
  106.     std::cin.get();
  107.  
  108.     return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment