Error pipe listening

Windows Named Pipe Test (Connection and Disconnection) - NamedPipeTest.cc
// Dedicated to the public domain as per the Creative Commons CC0 // (https://creativecommons.org/about/cc0/). // Compile with C++11 (i.e. -std=c++11) // Tests the behavior of Windows named pipes regarding the lifecycle of // connections. // // This test demonstrates various ways that Wine (as of 1.9.12) differs from // Windows: // // — With Windows, there can be multiple concurrent ConnectNamedPipe // operations on a pipe. With Wine, the second ConnectNamedPipe call fails // with ERROR_INVALID_HANDLE. // // — With Windows, DisconnectNamedPipe aborts ConnectNamedPipe operations with // the error ERROR_PIPE_NOT_CONNECTED. The DisconnectNamedPipe call // succeeds, and the pipe is no longer listening. With Wine, the // DisconnectNamedPipe call itself fails with ERROR_PIPE_LISTENING, and the // pipe is still listening. // // — With Windows, if the server breaks the pipe by closing its handle, the // client can finish reading the remaining data in the pipe. Once the data // is gone, reading from a broken pipe fails with ERROR_BROKEN_PIPE. // Writing to a broken pipe fails with ERROR_NO_DATA. With Wine, once the // server breaks the pipe, the client cannot read the remaining data, and // I/O on a broken pipe fails with ERROR_PIPE_NOT_CONNECTED. (Exception: // ReadFile on a server pipe still returns ERROR_BROKEN_PIPE.) // // — Calling ConnectNamedPipe on a broken server pipe fails with ERROR_NO_DATA // on Windows, but ERROR_NO_DATA_DETECTED on Wine. // #include <windows.h> #include <assert.h> #include <stdio.h> #include <string> #define CHECK(cond) do { if (!(cond)) { printf(«%s,%d: %s: CHECK failed: `%s`n«, __FILE__, __LINE__, __FUNCTION__, #cond); } } while (false) #define CHECK_SUCCESS(cond) do { if (!(cond)) { printf(«%s,%d: %s: API call unexpectedly failed: `%s`: « «LastError=%u%sn«, __FILE__, __LINE__, __FUNCTION__, #cond, static_cast<unsigned>(GetLastError()), stringFromError(GetLastError())); } } while (false) #define CHECK_FAILURE(cond, expectedErr) do { if (cond) { printf(«%s,%d: %s: API call unexpectedly succeeded: `%s`: « «expected error %u%sn«, __FILE__, __LINE__, __FUNCTION__, #cond, static_cast<unsigned>(expectedErr), stringFromError(expectedErr)); } else if (GetLastError() != expectedErr) { printf(«%s,%d: %s: API call failed with wrong error: `%s`: « «actual %u%s != expected %u%sn«, __FILE__, __LINE__, __FUNCTION__, #cond, static_cast<unsigned>(GetLastError()), stringFromError(GetLastError()), static_cast<unsigned>(expectedErr), stringFromError(expectedErr)); } } while (false) static const char *stringFromError(DWORD err) { switch (err) { case ERROR_INVALID_HANDLE: return «(ERROR_INVALID_HANDLE)«; // 6 case ERROR_BROKEN_PIPE: return «(ERROR_BROKEN_PIPE)«; // 109 case ERROR_NO_DATA: return «(ERROR_NO_DATA)«; // 232 case ERROR_PIPE_NOT_CONNECTED: return «(ERROR_PIPE_NOT_CONNECTED)«; // 233 case ERROR_PIPE_CONNECTED: return «(ERROR_PIPE_CONNECTED)«; // 535 case ERROR_PIPE_LISTENING: return «(ERROR_PIPE_LISTENING)«; // 536 case ERROR_IO_INCOMPLETE: return «(ERROR_IO_INCOMPLETE)«; // 996 case ERROR_IO_PENDING: return «(ERROR_IO_PENDING)«; // 997 case ERROR_NO_DATA_DETECTED: return «(ERROR_NO_DATA_DETECTED)«; // 1104 default: return ««; } } static std::string name(int idx) { return «\\.\pipe\NamedPipeTest« + std::to_string(idx); } static HANDLE openServer(const std::string &name, int maxInstances=1) { return CreateNamedPipeA( name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0, /*nMaxInstances=*/maxInstances, 256, 256, 0, nullptr); } static HANDLE createFile(const std::string &name) { return CreateFileA( name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); } static bool connectToServerAndClose(const std::string &name) { HANDLE handle = createFile(name); if (handle == INVALID_HANDLE_VALUE) { return false; } CloseHandle(handle); return true; } static HANDLE assertValid(HANDLE handle) { assert(handle != INVALID_HANDLE_VALUE); assert(handle != nullptr); return handle; } class Over : public OVERLAPPED { public: Over() { *(OVERLAPPED*)this = {}; hEvent = m_event = CreateEvent(nullptr, TRUE, FALSE, nullptr); assert(hEvent != nullptr); } ~Over() { assert(hEvent == m_event); CloseHandle(m_event); } private: HANDLE m_event; }; // A new server pipe can be connected to without first calling // ConnectNamedPipe, because a new pipe starts out in a «Listening» // state. static void testImplicitConnect() { const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); Over over; CHECK_FAILURE(ConnectNamedPipe(server, &over), ERROR_PIPE_CONNECTED); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(CloseHandle(server)); } // Calling DisconnectNamedPipe on a new pipe successfully transitions it to a // «Not Connected» state. The second DisconnectNamedPipe call fails, and the // client can’t connect. static void testDisconnectAtStartup() { const HANDLE server = assertValid(openServer(name(0))); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK(createFile(name(0)) == INVALID_HANDLE_VALUE); CHECK_FAILURE(DisconnectNamedPipe(server), ERROR_PIPE_NOT_CONNECTED); CHECK(createFile(name(0)) == INVALID_HANDLE_VALUE); CHECK_SUCCESS(CloseHandle(server)); } // A client can’t connect after the server has called DisconnectNamedPipe, // because the pipe is in a «Not Connected» state. static void testConnectAfterDisconnect() { const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK(createFile(name(0)) == INVALID_HANDLE_VALUE); CHECK_SUCCESS(CloseHandle(server)); CHECK_SUCCESS(CloseHandle(client)); } // Trying to connect after the client breaks the connection fails, because the // pipe is in some kind of «Broken / No Data» state. static void testReconnectAfterBreak() { const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(CloseHandle(client)); Over over; CHECK_FAILURE(ConnectNamedPipe(server, &over), ERROR_NO_DATA); CHECK_SUCCESS(CloseHandle(server)); } // Start connecting, asynchronously. Have a client connect, then immediately // break the connection, before the server checks the result of the async // operation. The operation should still have succeeded. static void testBreakBeforeAsyncCleanup() { DWORD dummyDW = 0; Over over; const HANDLE server = assertValid(openServer(name(0))); CHECK_FAILURE(ConnectNamedPipe(server, &over), ERROR_IO_PENDING); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(GetOverlappedResult(server, &over, &dummyDW, FALSE)); CHECK_SUCCESS(CloseHandle(server)); } static void testMultipleAyncConnectOpsStillSucceed() { DWORD dummyDW = 0; Over over1; Over over2; const HANDLE server = assertValid(openServer(name(0))); // Two connect operations, both pending CHECK_FAILURE(ConnectNamedPipe(server, &over1), ERROR_IO_PENDING); CHECK_FAILURE(ConnectNamedPipe(server, &over2), ERROR_IO_PENDING); const HANDLE client = assertValid(createFile(name(0))); // Now they’ve both succeeded. CHECK_SUCCESS(GetOverlappedResult(server, &over1, &dummyDW, FALSE)); CHECK_SUCCESS(GetOverlappedResult(server, &over2, &dummyDW, FALSE)); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(CloseHandle(server)); } static void testDisconnectAbortsConnectionAttempt() { DWORD dummyDW = 0; Over over; const HANDLE server = assertValid(openServer(name(0))); CHECK_FAILURE(ConnectNamedPipe(server, &over), ERROR_IO_PENDING); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK(!connectToServerAndClose(name(0))); CHECK_FAILURE(GetOverlappedResult(server, &over, &dummyDW, TRUE), ERROR_PIPE_NOT_CONNECTED); CHECK_SUCCESS(CloseHandle(server)); } static void testDisconnectAbortsReconnectionAttempt() { DWORD dummyDW = 0; Over over; // First connection. const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK_SUCCESS(CloseHandle(client)); // Reconnection attempt. CHECK_FAILURE(ConnectNamedPipe(server, &over), ERROR_IO_PENDING); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK(!connectToServerAndClose(name(0))); CHECK_FAILURE(GetOverlappedResult(server, &over, &dummyDW, TRUE), ERROR_PIPE_NOT_CONNECTED); CHECK_SUCCESS(CloseHandle(server)); } static void testDisconnectAbortsMultipleConnectionAttempts() { DWORD dummyDW = 0; Over over1; Over over2; const HANDLE server = assertValid(openServer(name(0))); CHECK_FAILURE(ConnectNamedPipe(server, &over1), ERROR_IO_PENDING); CHECK_FAILURE(ConnectNamedPipe(server, &over2), ERROR_IO_PENDING); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK(!connectToServerAndClose(name(0))); CHECK_FAILURE(GetOverlappedResult(server, &over1, &dummyDW, FALSE), ERROR_PIPE_NOT_CONNECTED); CHECK_FAILURE(GetOverlappedResult(server, &over2, &dummyDW, FALSE), ERROR_PIPE_NOT_CONNECTED); CHECK_SUCCESS(CloseHandle(server)); } static void testIoOnInitiallyUnconnectedServerPipe() { DWORD dummyDW = 0; Over over; char buf[1] = {}; const HANDLE server = assertValid(openServer(name(0))); CHECK_FAILURE(WriteFile(server, buf, 1, &dummyDW, &over), ERROR_PIPE_LISTENING); CHECK_FAILURE(ReadFile(server, buf, 1, &dummyDW, &over), ERROR_PIPE_LISTENING); CHECK_SUCCESS(CloseHandle(server)); } static void testIoOnBrokenServerPipe() { DWORD dummyDW = 0; Over over; char buf[1] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(CloseHandle(client)); CHECK_FAILURE(WriteFile(server, buf, 1, &dummyDW, &over), ERROR_NO_DATA); CHECK_FAILURE(ReadFile(server, buf, 1, &dummyDW, &over), ERROR_BROKEN_PIPE); CHECK_SUCCESS(CloseHandle(server)); } static void testIoOnBrokenClientPipe() { DWORD dummyDW = 0; Over over; char buf[1] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(CloseHandle(server)); CHECK_FAILURE(WriteFile(client, buf, 1, &dummyDW, &over), ERROR_NO_DATA); CHECK_FAILURE(ReadFile(client, buf, 1, &dummyDW, &over), ERROR_BROKEN_PIPE); CHECK_SUCCESS(CloseHandle(client)); } static void testIoOnDisconnectedClientPipe() { DWORD dummyDW = 0; Over over; char buf[1] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(DisconnectNamedPipe(server)); CHECK_FAILURE(WriteFile(client, buf, 1, &dummyDW, &over), ERROR_PIPE_NOT_CONNECTED); CHECK_FAILURE(ReadFile(client, buf, 1, &dummyDW, &over), ERROR_PIPE_NOT_CONNECTED); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(CloseHandle(server)); } // Windows creates I/O buffers for each pipe instance. DisconnectNamedPipe // kills the connection but keeps the I/O buffers for the next connection. // Therefore, any existing data is lost. static void testReadFromDisconnectedPipe() { DWORD dummyDW = 0; Over over; char buf[1] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(WriteFile(server, buf, 1, &dummyDW, &over)); DisconnectNamedPipe(server); CHECK_FAILURE(ReadFile(client, buf, 1, &dummyDW, &over), ERROR_PIPE_NOT_CONNECTED); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(CloseHandle(server)); } // If a server pipe is broken, the remaining data can still be read. static void testReadFromBrokenServerPipe() { DWORD actual = 0; Over over; char buf[2] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(WriteFile(client, buf, 1, &actual, &over)); CHECK_SUCCESS(CloseHandle(client)); CHECK_SUCCESS(ReadFile(server, buf, 2, &actual, &over)); CHECK(actual == 1); CHECK_FAILURE(ReadFile(server, buf, 2, &actual, &over), ERROR_BROKEN_PIPE); CHECK_SUCCESS(CloseHandle(server)); } // If a client pipe is broken, rather than disconnected, the remaining data can // still be read. static void testReadFromBrokenClientPipe() { DWORD actual = 0; Over over; char buf[2] = {}; const HANDLE server = assertValid(openServer(name(0))); const HANDLE client = assertValid(createFile(name(0))); CHECK_SUCCESS(WriteFile(server, buf, 1, &actual, &over)); CHECK_SUCCESS(CloseHandle(server)); CHECK_SUCCESS(ReadFile(client, buf, 2, &actual, &over)); CHECK(actual == 1); CHECK_FAILURE(ReadFile(client, buf, 2, &actual, &over), ERROR_BROKEN_PIPE); CHECK_SUCCESS(CloseHandle(client)); } // // XXX: This test fails on XP, but it passes on Vista, Win7, and Win10. // static void testChangeMaxInstancesAfterClosingLastServerHandle() { // Use a different pipe number here so that lingering handles can’t // interfere with the other tests. const HANDLE server = assertValid(openServer(name(1))); const HANDLE server2 = openServer(name(1), 2); CHECK(server2 == INVALID_HANDLE_VALUE); const HANDLE client = assertValid(createFile(name(1))); CHECK_SUCCESS(CloseHandle(server)); // There are no handles to the server pipe left open. We can change // the number of max instances. const HANDLE server3 = openServer(name(1), 2); const HANDLE server4 = openServer(name(1), 2); CHECK(server3 != INVALID_HANDLE_VALUE); CHECK(server4 != INVALID_HANDLE_VALUE); if (server2 != INVALID_HANDLE_VALUE) { CHECK_SUCCESS(CloseHandle(server2)); } if (server3 != INVALID_HANDLE_VALUE) { CHECK_SUCCESS(CloseHandle(server3)); } if (server4 != INVALID_HANDLE_VALUE) { CHECK_SUCCESS(CloseHandle(server4)); } CHECK_SUCCESS(CloseHandle(client)); } int main() { testImplicitConnect(); testDisconnectAtStartup(); testConnectAfterDisconnect(); testReconnectAfterBreak(); testBreakBeforeAsyncCleanup(); testMultipleAyncConnectOpsStillSucceed(); testDisconnectAbortsConnectionAttempt(); testDisconnectAbortsReconnectionAttempt(); testDisconnectAbortsMultipleConnectionAttempts(); testIoOnInitiallyUnconnectedServerPipe(); testIoOnBrokenServerPipe(); testIoOnBrokenClientPipe(); testIoOnDisconnectedClientPipe(); testReadFromDisconnectedPipe(); testReadFromBrokenServerPipe(); testReadFromBrokenClientPipe(); testChangeMaxInstancesAfterClosingLastServerHandle(); return 0; }

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Пайпы: ConnectNamedPipe не реагирует на подключение

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    09.06.10, 03:28

      Доброго всем дня. После вызова CreateNamedPipe с указанием асинхронного режима создаю событие, записываю его в Overlapped-структуру, ответвляюсь в новый поток и там вызываю WaitForSingleObject для ожидания подключения клиента. Но WaitForSingleObject не реагирует на подключение клиента.
      Сервер:

      ExpandedWrap disabled

        OVERLAPPED ovlGlobal;

        HANDLE hPipeGlobal;

        unsigned long int __stdcall ConnectNamedPipeThreadProc(void *parameter){

          ovlGlobal.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);

          ConnectNamedPipe(hPipeGlobal,&ovlGlobal);

          WaitForSingleObject(ovlGlobal.hEvent,INFINITE);

          /* зедсь находится вызов ReadFileEx */

        }

        void CreateButtonClick(){

          wchar_t pipepath[600]=L»\\.\pipe\123123″;

          hPipeGlobal = CreateNamedPipe(pipepath,

            PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE|FILE_FLAG_OVERLAPPED,

            PIPE_TYPE_MESSAGE|PIPE_NOWAIT,

            PIPE_UNLIMITED_INSTANCES,

            64*1024,

            64*1024,

            60*1000,

            NULL);

          CreateThread(NULL,0,ConnectNamedPipeThreadProc,NULL,0,NULL);

        }

      Клиент:

      ExpandedWrap disabled

        void ConnectButtonClick(){

          wchar_t pipename[600]=L»\\.\pipe\123123″;

          hPipeGlobal = CreateFile(pipepath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);

          /* здесь находится вызов ReadFileEx */

        }

      У всех системных вызовов смотрится возвращаемое значение, там ничего необычного.
      Как вы считаете, что здесь может быть не так?


      arj99



      Сообщ.
      #2

      ,
      09.06.10, 06:26

        Цитата Northsoft @ 09.06.10, 03:28

        У всех системных вызовов смотрится возвращаемое значение, там ничего необычного.

        Хорошо было бы «все обычное» привести здесь.
        А еще лучше смотреть эти значения не только в отладчике, а непосредственно в коде. Странно как-то просто, если смотрится — то почему в этом примере не отражено?.. :unsure:

        Цитата Northsoft @ 09.06.10, 03:28

        Как вы считаете, что здесь может быть не так?

        Я считаю, что нужно добавить инициализацию

        ExpandedWrap disabled

              OVERLAPPED ovlGlobal = { 0 };

        И, кстати, зачем она глобальная?
        Тот же вопрос относительно дескриптора канала. Лучше его в поток передавать параметром.


        Ace



        Сообщ.
        #3

        ,
        09.06.10, 06:44

          CreateNamedPipe удачно проходит?
          А что касаемо самого ожидания присоединения клиента, то лучше всёж проверять результаты выполняемых системных вызовов..

          ExpandedWrap disabled

            BOOL fConnect = ConnectNamedPipe(hPipeGlobal,&ovlGlobal);

            if( !fConnect && GetLastError() ==  ERROR_IO_PENDING)

               fConnect = WaitForSingleObject(ovlGlobal.hEvent,INFINITE) == WAIT_OBJECT_0;

            if( fConnect)

            {

            /* зедсь находится вызов ReadFileEx */

            }

            else { // Почему всё так плохо… }

          И проверяй удачу/неудачу создания файлов/потоков/событий/etc, и прочищай структуры перед их использованием в системных вызовах. Это избавит тебя от непредсказуемого поведения твоего кода и позволит намного быстрей находить место ошибки :)


          Northsoft



          Сообщ.
          #4

          ,
          09.06.10, 07:13

            Сервер:

            ExpandedWrap disabled

              unsigned long int __stdcall ConnectNamedPipeThreadProc(void *parameter){

                ovlGlobal.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); /* возвращено значение 0xDC */

                ConnectNamedPipe(hPipeGlobal,&ovlGlobal); /* возвращено значение 0, GetLastError()==ERROR_PIPE_LISTENING */

                WaitForSingleObject(ovlGlobal.hEvent,INFINITE); /* здесь функция блокирует поток */

                /* зедсь находится вызов ReadFileEx */

              }

              void CreateButtonClick(){

                wchar_t pipepath[600]=L»\\.\pipe\123123″;

                hPipeGlobal = CreateNamedPipe(pipepath,

                  PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE|FILE_FLAG_OVERLAPPED,

                  PIPE_TYPE_MESSAGE|PIPE_NOWAIT,

                  PIPE_UNLIMITED_INSTANCES,

                  64*1024,

                  64*1024,

                  60*1000,

                  NULL); /* возвращено значение 0xD8 */

                CreateThread(NULL,0,ConnectNamedPipeThreadProc,NULL,0,NULL);

              }

            Клиент:

            ExpandedWrap disabled

              void ConnectButtonClick(){

                wchar_t pipename[600]=L»\\.\pipe\123123″;

                hPipeGlobal = CreateFile(pipepath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL); /* возвращено значение 0xD4 */

                /* здесь находится вызов ReadFileEx */

              }

            Насчёт ERROR_PIPE_LISTENING было сказано в MSDN.
            З.Ы. Обнуление не помогло.

            Сообщение отредактировано: Northsoft — 09.06.10, 07:16

            0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

            0 пользователей:

            • Предыдущая тема
            • C/C++: Системное программирование и WinAPI
            • Следующая тема

            Рейтинг@Mail.ru

            [ Script execution time: 0,0331 ]   [ 16 queries used ]   [ Generated: 9.02.23, 14:59 GMT ]  

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            57
            58
            59
            60
            61
            62
            63
            64
            65
            66
            67
            68
            69
            70
            71
            72
            73
            74
            75
            76
            77
            78
            79
            80
            81
            82
            83
            84
            85
            86
            87
            88
            89
            90
            91
            92
            93
            94
            95
            96
            97
            98
            99
            100
            101
            102
            103
            104
            105
            106
            107
            108
            109
            110
            111
            112
            113
            114
            115
            116
            117
            118
            119
            120
            121
            122
            123
            124
            125
            126
            127
            128
            129
            130
            131
            132
            133
            134
            135
            136
            137
            138
            139
            140
            141
            142
            143
            144
            145
            146
            147
            148
            149
            150
            151
            152
            153
            154
            155
            156
            157
            158
            159
            160
            161
            162
            163
            164
            165
            166
            167
            168
            169
            170
            171
            172
            173
            174
            175
            176
            177
            178
            179
            180
            181
            182
            183
            184
            185
            186
            187
            188
            189
            
            #include <vcl.h>
            #include <conio.h>
            #include <iostream>
            #include <SyncObjs.hpp>
            #pragma hdrstop
             
            //---------------------------------------------------------------------------
             
            #pragma argsused
             
            using namespace std;
             
            AnsiString GetVerbalError (int lastError)
            {
                LPVOID lpMsgBuf;
                FormatMessage(
                    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                    NULL,
                    lastError,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                    (LPTSTR) &lpMsgBuf,
                    0,
                    NULL
                );
                AnsiString result ((const char *)lpMsgBuf);
                LocalFree(lpMsgBuf);
                return result;
            }
             
            AnsiString ToOem (AnsiString src)
            {
                char* buf = new char [src.Length() + 1];
                CharToOem(src.c_str(), buf);
                return AnsiString(buf);
            }
             
            void CommentConnection(int connect_error)
            {
                switch (connect_error) {
                    case ERROR_IO_PENDING:
                        cout << "connect_error = ERROR_IO_PENDING";
                        break;
                    case ERROR_PIPE_CONNECTED:
                        cout << "nconnect_error = ERROR_PIPE_CONNECTED";
                        break;
                    case ERROR_PIPE_LISTENING:
                        cout << "nconnect_error = ERROR_PIPE_LISTENING";
                        break;
                    default:
                        cout << AnsiString("nconnect_error = " + IntToStr(connect_error)).c_str();
                        break;
                }
            }
             
            bool EventSignaled (int wait_result)
            {
                switch (wait_result) {
                    case wrSignaled:
                        return true;
                    case wrTimeout:
                        return false;
                    case wrAbandoned:
                        throw Exception("waiting for event: wrAbandoned");
                    case wrError:
                        throw Exception("waiting for event: wrError");
                    default:
                        throw Exception("waiting for event: unexpected wait_result");
                }
            }
             
            int main(int argc, char* argv[])
            {
             
                const int BUF_SIZE = 1000;
                const int DEFAULT_WAIT_TIMEOUT = 100;
                HANDLE hPipe;
                TEvent* event = NULL;
                try {
                    try {
                        if (!(hPipe = CreateNamedPipe(AnsiString("\\.\pipe\MyPipe").c_str(),
                            PIPE_ACCESS_DUPLEX
                            | FILE_FLAG_OVERLAPPED
                            | WRITE_OWNER,
                            PIPE_TYPE_BYTE
                            | PIPE_READMODE_BYTE
                            | PIPE_WAIT,
                            1, // max number of NP instances
                            BUF_SIZE, // out buffer size
                            BUF_SIZE, // in buffer size
                            DEFAULT_WAIT_TIMEOUT, // default timeout
                            NULL))
                        ) {
                            throw Exception ("Pipe handle not granted. " + GetVerbalError(GetLastError()));
                        }
             
                        event = new TEvent(
                            NULL, // security attributes
                            true, // manual reset
                            false, // initial state nonsignaled
                            NULL
                        );
             
                        OVERLAPPED overlapped;
                        overlapped.Offset = 0;
                        overlapped.OffsetHigh = 0;
                        overlapped.hEvent = (void*)(event->Handle);
                        event->ResetEvent();
             
                        bool good_connection = true;
                        if ( ! ConnectNamedPipe(hPipe, &overlapped) ) {
                            int connect_error = GetLastError();
                            good_connection =
                                connect_error == ERROR_IO_PENDING
                                || connect_error == ERROR_PIPE_CONNECTED
                                || connect_error == ERROR_PIPE_LISTENING;
                            CommentConnection(connect_error);
                        } else {
                            cout << "nconnect_result Ok";
                        }
             
                        if ( ! good_connection ) {
                            Exception ("connection not established:"  + GetVerbalError(GetLastError()));
                        } else {
                            cout << "nWaiting for connect.";
                        }
             
                        while (!EventSignaled(event->WaitFor(DEFAULT_WAIT_TIMEOUT))) {
                            if (kbhit()) {
                                getch();
                                throw Exception ("User abort.");
                            }
                        }
                        cout << "nConnection established.";
             
                        char bufRead [BUF_SIZE];
                        char bufWrite [BUF_SIZE];
                        unsigned long numCharsRead;
                        event->ResetEvent();
                        bool transact_result = TransactNamedPipe(
                            hPipe,
                            bufWrite,
                            0,
                            bufRead,
                            BUF_SIZE,
                            &numCharsRead,
                            &overlapped
                        );
             
                        if (!transact_result && GetLastError() != ERROR_IO_PENDING) {
                            throw Exception ("TransactNamedPipe: " + GetVerbalError(GetLastError()));
                        }
             
                        while (!EventSignaled(event->WaitFor(DEFAULT_WAIT_TIMEOUT))) {
                            if (kbhit()) {
                                getch();
                                throw Exception ("User abort.");
                            }
                        }
             
                        TransactNamedPipe(
                            hPipe,
                            bufWrite,
                            0,
                            bufRead,
                            BUF_SIZE,
                            &numCharsRead,
                            &overlapped
                        );
             
                        cout << (AnsiString("nFinished succesfully. Read ") + IntToStr(numCharsRead) + " bytes.").c_str();
             
                    } catch (Exception &e) {
                        cout << "nException:" << ToOem(e.Message).c_str();
                    }
             
                } __finally {
                    if (event) {
                        delete event;
                    }
                    if (hPipe) {
                        CloseHandle (hPipe);
                    }
                    cout << "nHandle closed.";
                    getch();
                }
             
             
                return 0;
            }
            Code Description Name

            0

            The operation completed successfully.

            ERROR_SUCCESS

            1

            Incorrect function.

            ERROR_INVALID_FUNCTION

            2

            The system cannot find the file specified.

            ERROR_FILE_NOT_FOUND

            3

            The system cannot find the path specified.

            ERROR_PATH_NOT_FOUND

            4

            The system cannot open the file.

            ERROR_TOO_MANY_OPEN_FILES

            5

            Access is denied.

            ERROR_ACCESS_DENIED

            6

            The handle is invalid.

            ERROR_INVALID_HANDLE

            7

            The storage control blocks were destroyed.

            ERROR_ARENA_TRASHED

            8

            Not enough storage is available to process
            this command.

            ERROR_NOT_ENOUGH_MEMORY

            9

            The storage control block address is invalid.

            ERROR_INVALID_BLOCK

            10

            The environment is incorrect.

            ERROR_BAD_ENVIRONMENT

            11

            An attempt was made to load a program with
            an incorrect format.

            ERROR_BAD_FORMAT

            12

            The access code is invalid.

            ERROR_INVALID_ACCESS

            13

            The data is invalid.

            ERROR_INVALID_DATA

            14

            Not enough storage is available to complete
            this operation.

            ERROR_OUTOFMEMORY

            15

            The system cannot find the drive specified.

            ERROR_INVALID_DRIVE

            16

            The directory cannot be removed.

            ERROR_CURRENT_DIRECTORY

            17

            The system cannot move the file to a different
            disk drive.

            ERROR_NOT_SAME_DEVICE

            18

            There are no more files.

            ERROR_NO_MORE_FILES

            19

            The media is write protected.

            ERROR_WRITE_PROTECT

            20

            The system cannot find the device specified.

            ERROR_BAD_UNIT

            21

            The device is not ready.

            ERROR_NOT_READY

            22

            The device does not recognize the command.

            ERROR_BAD_COMMAND

            23

            Data error (cyclic redundancy check).

            ERROR_CRC

            24

            The program issued a command but the command
            length is incorrect.

            ERROR_BAD_LENGTH

            25

            The drive cannot locate a specific area or
            track on the disk.

            ERROR_SEEK

            26

            The specified disk or diskette cannot be accessed.

            ERROR_NOT_DOS_DISK

            27

            The drive cannot find the sector requested.

            ERROR_SECTOR_NOT_FOUND

            28

            The printer is out of paper.

            ERROR_OUT_OF_PAPER

            29

            The system cannot write to the specified device.

            ERROR_WRITE_FAULT

            30

            The system cannot read from the specified
            device.

            ERROR_READ_FAULT

            31

            A device attached to the system is not functioning.

            ERROR_GEN_FAILURE

            32

            The process cannot access the file because
            it is being used by another process.

            ERROR_SHARING_VIOLATION

            33

            The process cannot access the file because
            another process has locked a portion of the file.

            ERROR_LOCK_VIOLATION

            34

            The wrong diskette is in the drive. Insert
            %2 (Volume Serial Number: %3) into drive %1.

            ERROR_WRONG_DISK

            36

            Too many files opened for sharing.

            ERROR_SHARING_BUFFER_EXCEEDED

            38

            Reached the end of the file.

            ERROR_HANDLE_EOF

            39

            The disk is full.

            ERROR_HANDLE_DISK_FULL

            50

            The network request is not supported.

            ERROR_NOT_SUPPORTED

            51

            The remote computer is not available.

            ERROR_REM_NOT_LIST

            52

            A duplicate name exists on the network.

            ERROR_DUP_NAME

            53

            The network path was not found.

            ERROR_BAD_NETPATH

            54

            The network is busy.

            ERROR_NETWORK_BUSY

            55

            The specified network resource or device is
            no longer available.

            ERROR_DEV_NOT_EXIST

            56

            The network BIOS command limit has been reached.

            ERROR_TOO_MANY_CMDS

            57

            A network adapter hardware error occurred.

            ERROR_ADAP_HDW_ERR

            58

            The specified server cannot perform the requested
            operation.

            ERROR_BAD_NET_RESP

            59

            An unexpected network error occurred.

            ERROR_UNEXP_NET_ERR

            60

            The remote adapter is not compatible.

            ERROR_BAD_REM_ADAP

            61

            The printer queue is full.

            ERROR_PRINTQ_FULL

            62

            Space to store the file waiting to be printed
            is not available on the server.

            ERROR_NO_SPOOL_SPACE

            63

            Your file waiting to be printed was deleted.

            ERROR_PRINT_CANCELED

            64

            The specified network name is no longer available.

            ERROR_NETNAME_DELETED

            65

            Network access is denied.

            ERROR_NETWORK_ACCESS_DENIED

            66

            The network resource type is not correct.

            ERROR_BAD_DEV_TYPE

            67

            The network name cannot be found.

            ERROR_BAD_NET_NAME

            68

            The name limit for the local computer network
            adapter card was exceeded.

            ERROR_TOO_MANY_NAMES

            69

            The network BIOS session limit was exceeded.

            ERROR_TOO_MANY_SESS

            70

            The remote server has been paused or is in
            the process of being started.

            ERROR_SHARING_PAUSED

            71

            No more connections can be made to this remote
            computer at this time because there are already as many connections as
            the computer can accept.

            ERROR_REQ_NOT_ACCEP

            72

            The specified printer or disk device has been
            paused.

            ERROR_REDIR_PAUSED

            80

            The file exists.

            ERROR_FILE_EXISTS

            82

            The directory or file cannot be created.

            ERROR_CANNOT_MAKE

            83

            Fail on INT 24.

            ERROR_FAIL_I24

            84

            Storage to process this request is not available.

            ERROR_OUT_OF_STRUCTURES

            85

            The local device name is already in use.

            ERROR_ALREADY_ASSIGNED

            86

            The specified network passwordA secret combination of characters for a Automation Engine user. is not correct.

            ERROR_INVALID_PASSWORD

            87

            The parameter is incorrect.

            ERROR_INVALID_PARAMETER

            88

            A write fault occurred on the network.

            ERROR_NET_WRITE_FAULT

            89

            The system cannot start another process at
            this time.

            ERROR_NO_PROC_SLOTS

            100

            Cannot create another system semaphore.

            ERROR_TOO_MANY_SEMAPHORES

            101

            The exclusive semaphore is owned by another
            process.

            ERROR_EXCL_SEM_ALREADY_OWNED

            102

            The semaphore is set and cannot be closed.

            ERROR_SEM_IS_SET

            103

            The semaphore cannot be set again.

            ERROR_TOO_MANY_SEM_REQUESTS

            104

            Cannot request exclusive semaphores at interrupt
            time.

            ERROR_INVALID_AT_INTERRUPT_TIME

            105

            The previous ownership of this semaphore has
            ended.

            ERROR_SEM_OWNER_DIED

            106

            Insert the diskette for drive %1.

            ERROR_SEM_USER_LIMIT

            107

            The program stopped because an alternate diskette
            was not inserted.

            ERROR_DISK_CHANGE

            108

            The disk is in use or locked by another process.

            ERROR_DRIVE_LOCKED

            109

            The pipe has been ended.

            ERROR_BROKEN_PIPE

            110

            The system cannot open the device or file
            specified.

            ERROR_OPEN_FAILED

            111

            The file name is too long.

            ERROR_BUFFER_OVERFLOW

            112

            There is not enough space on the disk.

            ERROR_DISK_FULL

            113

            No more internal file identifiers available.

            ERROR_NO_MORE_SEARCH_HANDLES

            114

            The target internal file identifier is incorrect.

            ERROR_INVALID_TARGET_HANDLE

            117

            The IOCTL call made by the application program
            is not correct.

            ERROR_INVALID_CATEGORY

            118

            The verify-on-write switch parameter value
            is not correct.

            ERROR_INVALID_VERIFY_SWITCH

            119

            The system does not support the command requested.

            ERROR_BAD_DRIVER_LEVEL

            120

            This function is not supported on this system.

            ERROR_CALL_NOT_IMPLEMENTED

            121

            The semaphore timeout period has expired.

            ERROR_SEM_TIMEOUT

            122

            The data area passed to a system call is too
            small.

            ERROR_INSUFFICIENT_BUFFER

            123

            The filename, directory name, or volume label
            syntax is incorrect.

            ERROR_INVALID_NAME

            124

            The system call level is not correct.

            ERROR_INVALID_LEVEL

            125

            The disk has no volume label.

            ERROR_NO_VOLUME_LABEL

            126

            The specified module could not be found.

            ERROR_MOD_NOT_FOUND

            127

            The specified procedure could not be found.

            ERROR_PROC_NOT_FOUND

            128

            There are no child processes to wait for.

            ERROR_WAIT_NO_CHILDREN

            129

            The %1 application cannot be run in Win32
            mode.

            ERROR_CHILD_NOT_COMPLETE

            130

            Attempt to use a file handle to an open disk
            partition for an operation other than raw disk I/O.

            ERROR_DIRECT_ACCESS_HANDLE

            131

            An attempt was made to move the file pointer
            before the beginning of the file.

            ERROR_NEGATIVE_SEEK

            132

            The file pointer cannot be set on the specified
            device or file.

            ERROR_SEEK_ON_DEVICE

            133

            A JOIN or SUBST command cannot be used for
            a drive that contains previously joined drives.

            ERROR_IS_JOIN_TARGET

            134

            An attempt was made to use a JOIN or SUBST
            command on a drive that has already been joined.

            ERROR_IS_JOINED

            135

            An attempt was made to use a JOIN or SUBST
            command on a drive that has already been substituted.

            ERROR_IS_SUBSTED

            136

            The system tried to delete the JOIN of a drive
            that is not joined.

            ERROR_NOT_JOINED

            137

            The system tried to delete the substitution
            of a drive that is not substituted.

            ERROR_NOT_SUBSTED

            138

            The system tried to join a drive to a directory
            on a joined drive.

            ERROR_JOIN_TO_JOIN

            139

            The system tried to substitute a drive to
            a directory on a substituted drive.

            ERROR_SUBST_TO_SUBST

            140

            The system tried to join a drive to a directory
            on a substituted drive.

            ERROR_JOIN_TO_SUBST

            141

            The system tried to SUBST a drive to a directory
            on a joined drive.

            ERROR_SUBST_TO_JOIN

            142

            The system cannot perform a JOIN or SUBST
            at this time.

            ERROR_BUSY_DRIVE

            143

            The system cannot join or substitute a drive
            to or for a directory on the same drive.

            ERROR_SAME_DRIVE

            144

            The directory is not a subdirectory of the
            root directory.

            ERROR_DIR_NOT_ROOT

            145

            The directory is not empty.

            ERROR_DIR_NOT_EMPTY

            146

            The path specified is being used in a substitute.

            ERROR_IS_SUBST_PATH

            147

            Not enough resources are available to process
            this command.

            ERROR_IS_JOIN_PATH

            148

            The path specified cannot be used at this
            time.

            ERROR_PATH_BUSY

            149

            An attempt was made to join or substitute
            a drive for which a directory on the drive is the target of a previous
            substitute.

            ERROR_IS_SUBST_TARGET

            150

            System trace information was not specified
            in your CONFIG.SYS file, or tracing is disallowed.

            ERROR_SYSTEM_TRACE

            151

            The number of specified semaphore events for
            DosMuxSemWait is not correct.

            ERROR_INVALID_EVENT_COUNT

            152

            DosMuxSemWait did not execute; too many semaphores
            are already set.

            ERROR_TOO_MANY_MUXWAITERS

            153

            The DosMuxSemWait list is not correct.

            ERROR_INVALID_LIST_FORMAT

            154

            The volume label you entered exceeds the label
            character limit of the target file system.

            ERROR_LABEL_TOO_LONG

            155

            Cannot create another thread.

            ERROR_TOO_MANY_TCBS

            156

            The recipient process has refused the signal.

            ERROR_SIGNAL_REFUSED

            157

            The segment is already discarded and cannot
            be locked.

            ERROR_DISCARDED

            158

            The segment is already unlocked.

            ERROR_NOT_LOCKED

            159

            The address for the thread ID is not correct.

            ERROR_BAD_THREADID_ADDR

            160

            The argument string passed to DosExecPgm is
            not correct.

            ERROR_BAD_ARGUMENTS

            161

            The specified path is invalid.

            ERROR_BAD_PATHNAME

            162

            A signal is already pending.

            ERROR_SIGNAL_PENDING

            164

            No more threads can be created in the system.

            ERROR_MAX_THRDS_REACHED

            167

            Unable to lock a region of a file.

            ERROR_LOCK_FAILED

            170

            The requested resource is in use.

            ERROR_BUSY

            173

            A lock request was not outstanding for the
            supplied cancel region.

            ERROR_CANCEL_VIOLATION

            174

            The file system does not support atomic changes
            to the lock type.

            ERROR_ATOMIC_LOCKS_NOT_SUPPORTED

            180

            The system detected a segment number that
            was not correct.

            ERROR_INVALID_SEGMENT_NUMBER

            182

            The operating system cannot run %1.

            ERROR_INVALID_ORDINAL

            183

            Cannot create a file when that file already
            exists.

            ERROR_ALREADY_EXISTS

            186

            The flag passed is not correct.

            ERROR_INVALID_FLAG_NUMBER

            187

            The specified system semaphore name was not
            found.

            ERROR_SEM_NOT_FOUND

            188

            The operating system cannot run %1.

            ERROR_INVALID_STARTING_CODESEG

            189

            The operating system cannot run %1.

            ERROR_INVALID_STACKSEG

            190

            The operating system cannot run %1.

            ERROR_INVALID_MODULETYPE

            191

            Cannot run %1 in Win32 mode.

            ERROR_INVALID_EXE_SIGNATURE

            192

            The operating system cannot run %1.

            ERROR_EXE_MARKED_INVALID

            193

            %1 is not a valid Win32 application.

            ERROR_BAD_EXE_FORMAT

            194

            The operating system cannot run %1.

            ERROR_ITERATED_DATA_EXCEEDS_64k

            195

            The operating system cannot run %1.

            ERROR_INVALID_MINALLOCSIZE

            196

            The operating system cannot run this application
            program.

            ERROR_DYNLINK_FROM_INVALID_RING

            197

            The operating system is not presently configured
            to run this application.

            ERROR_IOPL_NOT_ENABLED

            198

            The operating system cannot run %1.

            ERROR_INVALID_SEGDPL

            199

            The operating system cannot run this application
            program.

            ERROR_AUTODATASEG_EXCEEDS_64k

            200

            The code segment cannot be greater than or
            equal to 64K.

            ERROR_RING2SEG_MUST_BE_MOVABLE

            201

            The operating system cannot run %1.

            ERROR_RELOC_CHAIN_XEEDS_SEGLIM

            202

            The operating system cannot run %1.

            ERROR_INFLOOP_IN_RELOC_CHAIN

            203

            The system could not find the environment
            option that was entered.

            ERROR_ENVVAR_NOT_FOUND

            205

            No process in the command subtree has a signal
            handler.

            ERROR_NO_SIGNAL_SENT

            206

            The filename or extension is too long.

            ERROR_FILENAME_EXCED_RANGE

            207

            The ring 2 stack is in use.

            ERROR_RING2_STACK_IN_USE

            208

            The global filename characters, * or ?, are
            entered incorrectly or too many global filename characters are specified.

            ERROR_META_EXPANSION_TOO_LONG

            209

            The signal being posted is not correct.

            ERROR_INVALID_SIGNAL_NUMBER

            210

            The signal handler cannot be set.

            ERROR_THREAD_1_INACTIVE

            212

            The segment is locked and cannot be reallocated.

            ERROR_LOCKED

            214

            Too many dynamic-link modules are attached
            to this program or dynamic-link module.

            ERROR_TOO_MANY_MODULES

            215

            Cannot nest calls to LoadModule.

            ERROR_NESTING_NOT_ALLOWED

            216

            The image file %1 is valid, but is for a machine
            type other than the current machine.

            ERROR_EXE_MACHINE_TYPE_MISMATCH

            230

            The pipe state is invalid.

            ERROR_BAD_PIPE

            231

            All pipe instances are busy.

            ERROR_PIPE_BUSY

            232

            The pipe is being closed.

            ERROR_NO_DATA

            233

            No process is on the other end of the pipe.

            ERROR_PIPE_NOT_CONNECTED

            234

            More data is available.

            ERROR_MORE_DATA

            240

            The session was canceled.

            ERROR_VC_DISCONNECTED

            254

            The specified extended attribute name was
            invalid.

            ERROR_INVALID_EA_NAME

            255

            The extended attributes are inconsistent.

            ERROR_EA_LIST_INCONSISTENT

            258

            The wait operation timed out.

            WAIT_TIMEOUT

            259

            No more data is available.

            ERROR_NO_MORE_ITEMS

            266

            The copy functions cannot be used.

            ERROR_CANNOT_COPY

            267

            The directory name is invalid.

            ERROR_DIRECTORY

            275

            The extended attributes did not fit in the
            buffer.

            ERROR_EAS_DIDNT_FIT

            276

            The extended attribute file on the mounted
            file system is corrupt.

            ERROR_EA_FILE_CORRUPT

            277

            The extended attribute table file is full.

            ERROR_EA_TABLE_FULL

            278

            The specified extended attribute handle is
            invalid.

            ERROR_INVALID_EA_HANDLE

            282

            The mounted file system does not support extended
            attributes.

            ERROR_EAS_NOT_SUPPORTED

            288

            Attempt to release mutex not owned by caller.

            ERROR_NOT_OWNER

            298

            Too many posts were made to a semaphore.

            ERROR_TOO_MANY_POSTS

            299

            Only part of a ReadProcessMemory or WriteProcessMemory
            request was completed.

            ERROR_PARTIAL_COPY

            300

            The oplock request is denied.

            ERROR_OPLOCK_NOT_GRANTED

            301

            An invalid oplock acknowledgment was received
            by the system.

            ERROR_INVALID_OPLOCK_PROTOCOL

            317

            The system cannot find message text for message
            number 0x%1 in the message file for %2.

            ERROR_MR_MID_NOT_FOUND

            487

            Attempt to access invalid address.

            ERROR_INVALID_ADDRESS

            534

            Arithmetic result exceeded 32 bits.

            ERROR_ARITHMETIC_OVERFLOW

            535

            There is a process on other end of the pipe.

            ERROR_PIPE_CONNECTED

            536

            Waiting for a process to open the other end
            of the pipe.

            ERROR_PIPE_LISTENING

            994

            Access to the extended attribute was denied.

            ERROR_EA_ACCESS_DENIED

            995

            The I/O operation has been aborted because
            of either a thread exit or an application request.

            ERROR_OPERATION_ABORTED

            996

            Overlapped I/O event is not in a signaled
            state.

            ERROR_IO_INCOMPLETE

            997

            Overlapped I/O operation is in progress.

            ERROR_IO_PENDING

            998

            Invalid access to memory location.

            ERROR_NOACCESS

            999

            Error performing inpage operation. 

            ERROR_SWAPERROR 

            Понравилась статья? Поделить с друзьями:
          • Error php для joomla
          • Error php startup unable to load dynamic library
          • Error php is not running wordpress
          • Error php home is not specified or invalid press fix to edit your project configuration
          • Error phone code invalid