From a781ef145378785397dddb2f4cc7d4dbb2fdda98 Mon Sep 17 00:00:00 2001 From: visionmercer <62051836+visionmercer@users.noreply.github.com> Date: Tue, 23 Jun 2026 12:40:40 +0200 Subject: [PATCH] Getting better --- terminkey.h | 48 +++++++++++++++++++++--------------------------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/terminkey.h b/terminkey.h index d6b9d9a..cacf060 100644 --- a/terminkey.h +++ b/terminkey.h @@ -86,12 +86,10 @@ int termwidth() { } int ipc_init() { - // Remove PIPE_NOWAIT so the pipe handles state transmissions reliably. - // We will handle non-blocking checks manually using PeekNamedPipe. hServerPipe = CreateNamedPipe( "\\\\.\\pipe\\cimp_ipc", PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, - PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT, // Enable non-blocking wait mode 1, 4096, 4096, @@ -113,34 +111,30 @@ int ipc_check_message(uintptr_t buffer_ptr, int max_len) { char* buffer = (char*)buffer_ptr; DWORD bytesRead = 0; - DWORD bytesAvail = 0; - - // Use PeekNamedPipe to see if a client has connected and written data - // without blocking the main QB64 execution loop. - if (PeekNamedPipe(hServerPipe, NULL, 0, NULL, &bytesAvail, NULL)) { - if (bytesAvail > 0) { - // Data is waiting! Safely read it. - BOOL success = ReadFile(hServerPipe, buffer, max_len - 1, &bytesRead, NULL); - if (success && bytesRead > 0) { - buffer[bytesRead] = '\0'; - - // Disconnect and immediately reconnect to reset the pipe state for the next client + + // In non-blocking mode, ConnectNamedPipe returns immediately. + // If a client is connected, it returns non-zero, or zero with ERROR_PIPE_CONNECTED. + BOOL connected = ConnectNamedPipe(hServerPipe, NULL) ? + TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); + + if (connected) { + DWORD bytesAvail = 0; + // Verify that data has safely populated the buffer before reading + if (PeekNamedPipe(hServerPipe, NULL, 0, NULL, &bytesAvail, NULL)) { + if (bytesAvail > 0) { + BOOL success = ReadFile(hServerPipe, buffer, max_len - 1, &bytesRead, NULL); + if (success && bytesRead > 0) { + buffer[bytesRead] = '\0'; + DisconnectNamedPipe(hServerPipe); // Reset pipe state for the next command + return (int)bytesRead; + } + } + } else { + if (GetLastError() == ERROR_BROKEN_PIPE) { DisconnectNamedPipe(hServerPipe); - return (int)bytesRead; } } - } else { - // If Peek fails because a client connected but broke the pipe/disconnected - DWORD err = GetLastError(); - if (err == ERROR_BROKEN_PIPE) { - DisconnectNamedPipe(hServerPipe); - } } - - // Non-blocking fallback: try to listen for the next incoming connection choice - // strictly if the pipe is currently completely idle. - ConnectNamedPipe(hServerPipe, NULL); - return 0; }