Loading src/event/poll.cpp +146 −12 Changes for src/event/poll.cpp: 146 added lines, 12 removed lines. Original line number Diff line number Diff line Loading @@ -31,10 +31,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> #include <memory_resource> // Conditional Includes for Windows/POSIX #ifdef _WIN32 #include <winsock2.h> // For Sockets, select, timeval, FD_ macros, WSAStartup #include <windows.h> // For CreateThread, GetSystemInfo, HANDLE, etc. #include <process.h> // For _beginthreadex (safer than CreateThread) #include <io.h> // For _close (if needed, but closesocket is preferred) #include <cstdio> // For std::snprintf // Redefine POSIX functions/types to Windows equivalents #define close(fd) closesocket(fd) #define GET_LAST_ERROR() WSAGetLastError() #define O_NONBLOCK 0x800 typedef SSIZE_T ssize_t; typedef int socklen_t; // Define pthread types to Windows types for compilation typedef HANDLE pthread_t; // pthread_attr_t is not strictly needed for CreateThread struct pthread_attr_t {}; #define pthread_attr_init(a) 0 #define pthread_attr_destroy(a) // Simple implementation of pthread_join for HANDLE #define pthread_join(t, r) (WaitForSingleObject(t, INFINITE) == WAIT_OBJECT_0 ? 0 : -1) // Minimal implementation of strerror_r_netplus for Windows/Winsock errors inline void strerror_r_netplus(int errnum, char *buf, size_t buflen) { if (errnum != 0) { std::snprintf(buf, buflen, "WinSock Error %d", errnum); } else { std::strncpy(buf, "No error", buflen); buf[buflen - 1] = '\0'; } } #else #include <unistd.h> #include <signal.h> #include <sys/select.h> // Standard POSIX select #include <fcntl.h> #include <pthread.h> // For pthread_t and related functions // Assuming "../posix/error.h" defines strerror_r_netplus for POSIX #endif #include <stdlib.h> #include <stdint.h> #include <mutex> Loading @@ -48,7 +88,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "eventapi.h" #include "connection.h" // Conditional inclusion of a custom error header #ifndef _WIN32 #include "../posix/error.h" #endif #include <assert.h> Loading Loading @@ -157,7 +200,6 @@ namespace netplus { } // Update the master sets based on the requested event flags // EPOLLONESHOT is simulated by clearing the other set // Clear any existing interests FD_CLR(fd, &_masterReadSet); Loading Loading @@ -194,14 +236,30 @@ namespace netplus { tv.tv_usec = (timeout % 1000) * 1000; // 2. Call select() int nready = select(_maxFD + 1, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); int nready; #ifdef _WIN32 // On Windows, the first argument (nfds) is ignored, set to 0. nready = select(0, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); #else nready = select(_maxFD + 1, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); #endif if (nready < 0) { if (errno == EINTR) { int error_code; #ifdef _WIN32 error_code = GET_LAST_ERROR(); if (error_code == WSAEINTR) { return 0; // Interrupted by signal } #else error_code = errno; if (error_code == EINTR) { return 0; // Interrupted by signal } #endif char str[255]; strerror_r_netplus(errno,str,255); strerror_r_netplus(error_code,str,255); exception[NetException::Error] << "waitEventHandler: select failure: " << str; throw exception; } Loading @@ -210,13 +268,17 @@ namespace netplus { } // 3. Populate _ReadyEvents list based on which FDs are set in the current sets // Iterate up to _maxFD (correct for both POSIX and as an upper bound for Windows) for (int fd = 0; fd <= _maxFD; ++fd) { int event_flags = 0; // Check for activity in any of the sets if (FD_ISSET(fd, &_currentReadSet) || FD_ISSET(fd, &_currentWriteSet) || FD_ISSET(fd, &_currentExceptSet)) { if (FD_ISSET(fd, &_currentReadSet)) { // Check if it's the server socket (new connection) if (fd == _ServerSocket->fd()) { // Special handling for connect event, which is EVCON for the EventWorker // Special handling for connect event _ReadyEvents.push_back({fd, EventHandlerStatus::EVCON}); continue; } Loading @@ -231,6 +293,7 @@ namespace netplus { // Treat exception/error as close event event_flags |= (EPOLLERR | EPOLLHUP); } } if (event_flags != 0) { _ReadyEvents.push_back({fd, event_flags}); Loading @@ -248,7 +311,7 @@ namespace netplus { if(!ccon){ char errstr[255]; strerror_r_netplus(errno,errstr,255); strerror_r_netplus(GET_LAST_ERROR(), errstr, 255); std::cerr << "ConnectEventHandler: Failed to accept connection or invalid connection object: " << errstr << std::endl; return; } Loading @@ -263,7 +326,7 @@ namespace netplus { if (!ccon->csock) { char errstr[255]; strerror_r_netplus(errno,errstr,255); strerror_r_netplus(GET_LAST_ERROR(),errstr,255); std::cerr << "ConnectEventHandler: Failed to create socket object: " << errstr << std::endl; return; } Loading Loading @@ -329,7 +392,7 @@ namespace netplus { return; } // If nothing to send, stay in Read mode. No action needed if EPOLLONESHOT is simulated by the change logic. // If nothing to send, stay in Read mode. }catch(NetException &e){ if(e.getErrorType()== NetException::Note){ // Note suggests temporary issue, stay in read mode Loading Loading @@ -383,7 +446,7 @@ namespace netplus { wcon->lasteventime = time(nullptr); // Stay in Write mode. No action needed if EPOLLONESHOT is simulated by the change logic. // Stay in Write mode. }catch(NetException &e){ if(e.getErrorType()== NetException::Note){ return; Loading Loading @@ -416,8 +479,9 @@ namespace netplus { FD_CLR(ccon->csock->fd(), &_masterWriteSet); FD_CLR(ccon->csock->fd(), &_masterExceptSet); // 2. Perform disconnect event // 2. Perform disconnect event and close socket evconnection->DisconnectEvent(*ccon, tid, args); ccon->csock->close(); } catch (NetException &e) { throw e; Loading Loading @@ -552,6 +616,26 @@ namespace netplus { int tid; }; #ifdef _WIN32 // Windows thread function signature DWORD WINAPI worker_wrapper(LPVOID data) { ThreadHelperArgs* helper_args = reinterpret_cast<ThreadHelperArgs*>(data); try { // Call the original worker function EventWorker(helper_args->tid, helper_args->args, helper_args->eargs); } catch (NetException& e) { std::cerr << "Thread " << helper_args->tid << " exited with exception: " << e.what() << std::endl; } catch (...) { std::cerr << "Thread " << helper_args->tid << " exited with unknown exception." << std::endl; } // Clean up allocated memory delete helper_args; return 0; // Windows thread function returns DWORD } #else // POSIX thread function signature void* worker_wrapper(void* data) { ThreadHelperArgs* helper_args = reinterpret_cast<ThreadHelperArgs*>(data); Loading @@ -568,6 +652,7 @@ namespace netplus { delete helper_args; return nullptr; } #endif void eventapi::RequestEvent(con &curcon,const int tid,ULONG_PTR args){ //dummy Loading Loading @@ -595,13 +680,26 @@ namespace netplus { _ServerSocket->bind(); _ServerSocket->setNonBlock(); _ServerSocket->listen(); #ifdef _WIN32 // Get number of processors on Windows SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); threads = sysinfo.dwNumberOfProcessors; #else // Get number of processors on POSIX threads=sysconf(_SC_NPROCESSORS_ONLN); #endif } event::event(const event &src) : _ServerSocket(src._ServerSocket) { } event::~event() { // Cleanup Winsock on Windows #ifdef _WIN32 WSACleanup(); #endif } void signalHandler(int signum) { Loading @@ -627,8 +725,19 @@ namespace netplus { void event::runEventloop(ULONG_PTR args) { NetException exception; // Initialize Winsock on Windows #ifdef _WIN32 WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { exception[NetException::Critical] << "runEventloop: WSAStartup failed: " << iResult; throw exception; } // Signal handling for SIGPIPE/SIGINT is different on Windows, keeping POSIX only for POSIX #else signal(SIGINT, signalHandler); signal(SIGPIPE, SIG_IGN); #endif MAINWORKERLOOP: // _pollFD is vestigial from the epoll implementation and is ignored in select. Loading @@ -642,17 +751,21 @@ namespace netplus { pthread_attr_t attr; if (pthread_attr_init(&attr) != 0) { #ifndef _WIN32 exception[NetException::Critical] << "runEventloop: Failed to initialize pthread attributes: " << strerror(errno); throw exception; #endif } // NOTE: THREAD_STACK_SIZE is an external constant. // Uncomment the following block if THREAD_STACK_SIZE is defined in your environment. /* if (pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE) != 0) { #ifndef _WIN32 exception[NetException::Critical] << "runEventloop: Failed to set pthread stack size: " << strerror(errno); pthread_attr_destroy(&attr); throw exception; #endif } */ Loading @@ -665,13 +778,34 @@ namespace netplus { ThreadHelperArgs *helper_args = new ThreadHelperArgs{&eargs, args, i}; pthread_t thread_id; // Use pthread_create with the custom attributes and C-style wrapper int ret = pthread_create(&thread_id, &attr, worker_wrapper, helper_args); int ret = 0; #ifdef _WIN32 // Windows Threading: CreateThread (or _beginthreadex) thread_id = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE)worker_wrapper, // thread function helper_args, // thread argument 0, // default creation flags NULL); // thread id (optional) if (thread_id == NULL) { ret = GetLastError(); } #else // POSIX Threading ret = pthread_create(&thread_id, &attr, worker_wrapper, helper_args); #endif if (ret != 0) { delete helper_args; // Cleanup allocated arguments char errstr[255]; #ifdef _WIN32 strerror_r_netplus(ret, errstr, 255); // Use WinSock-style error wrapper #else strerror_r(ret, errstr, 255); #endif exception[NetException::Critical] << "runEventloop: Failed to create thread: " << errstr; pthread_attr_destroy(&attr); throw exception; Loading Loading
src/event/poll.cpp +146 −12 Changes for src/event/poll.cpp: 146 added lines, 12 removed lines. Original line number Diff line number Diff line Loading @@ -31,10 +31,50 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> #include <memory_resource> // Conditional Includes for Windows/POSIX #ifdef _WIN32 #include <winsock2.h> // For Sockets, select, timeval, FD_ macros, WSAStartup #include <windows.h> // For CreateThread, GetSystemInfo, HANDLE, etc. #include <process.h> // For _beginthreadex (safer than CreateThread) #include <io.h> // For _close (if needed, but closesocket is preferred) #include <cstdio> // For std::snprintf // Redefine POSIX functions/types to Windows equivalents #define close(fd) closesocket(fd) #define GET_LAST_ERROR() WSAGetLastError() #define O_NONBLOCK 0x800 typedef SSIZE_T ssize_t; typedef int socklen_t; // Define pthread types to Windows types for compilation typedef HANDLE pthread_t; // pthread_attr_t is not strictly needed for CreateThread struct pthread_attr_t {}; #define pthread_attr_init(a) 0 #define pthread_attr_destroy(a) // Simple implementation of pthread_join for HANDLE #define pthread_join(t, r) (WaitForSingleObject(t, INFINITE) == WAIT_OBJECT_0 ? 0 : -1) // Minimal implementation of strerror_r_netplus for Windows/Winsock errors inline void strerror_r_netplus(int errnum, char *buf, size_t buflen) { if (errnum != 0) { std::snprintf(buf, buflen, "WinSock Error %d", errnum); } else { std::strncpy(buf, "No error", buflen); buf[buflen - 1] = '\0'; } } #else #include <unistd.h> #include <signal.h> #include <sys/select.h> // Standard POSIX select #include <fcntl.h> #include <pthread.h> // For pthread_t and related functions // Assuming "../posix/error.h" defines strerror_r_netplus for POSIX #endif #include <stdlib.h> #include <stdint.h> #include <mutex> Loading @@ -48,7 +88,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "eventapi.h" #include "connection.h" // Conditional inclusion of a custom error header #ifndef _WIN32 #include "../posix/error.h" #endif #include <assert.h> Loading Loading @@ -157,7 +200,6 @@ namespace netplus { } // Update the master sets based on the requested event flags // EPOLLONESHOT is simulated by clearing the other set // Clear any existing interests FD_CLR(fd, &_masterReadSet); Loading Loading @@ -194,14 +236,30 @@ namespace netplus { tv.tv_usec = (timeout % 1000) * 1000; // 2. Call select() int nready = select(_maxFD + 1, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); int nready; #ifdef _WIN32 // On Windows, the first argument (nfds) is ignored, set to 0. nready = select(0, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); #else nready = select(_maxFD + 1, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv); #endif if (nready < 0) { if (errno == EINTR) { int error_code; #ifdef _WIN32 error_code = GET_LAST_ERROR(); if (error_code == WSAEINTR) { return 0; // Interrupted by signal } #else error_code = errno; if (error_code == EINTR) { return 0; // Interrupted by signal } #endif char str[255]; strerror_r_netplus(errno,str,255); strerror_r_netplus(error_code,str,255); exception[NetException::Error] << "waitEventHandler: select failure: " << str; throw exception; } Loading @@ -210,13 +268,17 @@ namespace netplus { } // 3. Populate _ReadyEvents list based on which FDs are set in the current sets // Iterate up to _maxFD (correct for both POSIX and as an upper bound for Windows) for (int fd = 0; fd <= _maxFD; ++fd) { int event_flags = 0; // Check for activity in any of the sets if (FD_ISSET(fd, &_currentReadSet) || FD_ISSET(fd, &_currentWriteSet) || FD_ISSET(fd, &_currentExceptSet)) { if (FD_ISSET(fd, &_currentReadSet)) { // Check if it's the server socket (new connection) if (fd == _ServerSocket->fd()) { // Special handling for connect event, which is EVCON for the EventWorker // Special handling for connect event _ReadyEvents.push_back({fd, EventHandlerStatus::EVCON}); continue; } Loading @@ -231,6 +293,7 @@ namespace netplus { // Treat exception/error as close event event_flags |= (EPOLLERR | EPOLLHUP); } } if (event_flags != 0) { _ReadyEvents.push_back({fd, event_flags}); Loading @@ -248,7 +311,7 @@ namespace netplus { if(!ccon){ char errstr[255]; strerror_r_netplus(errno,errstr,255); strerror_r_netplus(GET_LAST_ERROR(), errstr, 255); std::cerr << "ConnectEventHandler: Failed to accept connection or invalid connection object: " << errstr << std::endl; return; } Loading @@ -263,7 +326,7 @@ namespace netplus { if (!ccon->csock) { char errstr[255]; strerror_r_netplus(errno,errstr,255); strerror_r_netplus(GET_LAST_ERROR(),errstr,255); std::cerr << "ConnectEventHandler: Failed to create socket object: " << errstr << std::endl; return; } Loading Loading @@ -329,7 +392,7 @@ namespace netplus { return; } // If nothing to send, stay in Read mode. No action needed if EPOLLONESHOT is simulated by the change logic. // If nothing to send, stay in Read mode. }catch(NetException &e){ if(e.getErrorType()== NetException::Note){ // Note suggests temporary issue, stay in read mode Loading Loading @@ -383,7 +446,7 @@ namespace netplus { wcon->lasteventime = time(nullptr); // Stay in Write mode. No action needed if EPOLLONESHOT is simulated by the change logic. // Stay in Write mode. }catch(NetException &e){ if(e.getErrorType()== NetException::Note){ return; Loading Loading @@ -416,8 +479,9 @@ namespace netplus { FD_CLR(ccon->csock->fd(), &_masterWriteSet); FD_CLR(ccon->csock->fd(), &_masterExceptSet); // 2. Perform disconnect event // 2. Perform disconnect event and close socket evconnection->DisconnectEvent(*ccon, tid, args); ccon->csock->close(); } catch (NetException &e) { throw e; Loading Loading @@ -552,6 +616,26 @@ namespace netplus { int tid; }; #ifdef _WIN32 // Windows thread function signature DWORD WINAPI worker_wrapper(LPVOID data) { ThreadHelperArgs* helper_args = reinterpret_cast<ThreadHelperArgs*>(data); try { // Call the original worker function EventWorker(helper_args->tid, helper_args->args, helper_args->eargs); } catch (NetException& e) { std::cerr << "Thread " << helper_args->tid << " exited with exception: " << e.what() << std::endl; } catch (...) { std::cerr << "Thread " << helper_args->tid << " exited with unknown exception." << std::endl; } // Clean up allocated memory delete helper_args; return 0; // Windows thread function returns DWORD } #else // POSIX thread function signature void* worker_wrapper(void* data) { ThreadHelperArgs* helper_args = reinterpret_cast<ThreadHelperArgs*>(data); Loading @@ -568,6 +652,7 @@ namespace netplus { delete helper_args; return nullptr; } #endif void eventapi::RequestEvent(con &curcon,const int tid,ULONG_PTR args){ //dummy Loading Loading @@ -595,13 +680,26 @@ namespace netplus { _ServerSocket->bind(); _ServerSocket->setNonBlock(); _ServerSocket->listen(); #ifdef _WIN32 // Get number of processors on Windows SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); threads = sysinfo.dwNumberOfProcessors; #else // Get number of processors on POSIX threads=sysconf(_SC_NPROCESSORS_ONLN); #endif } event::event(const event &src) : _ServerSocket(src._ServerSocket) { } event::~event() { // Cleanup Winsock on Windows #ifdef _WIN32 WSACleanup(); #endif } void signalHandler(int signum) { Loading @@ -627,8 +725,19 @@ namespace netplus { void event::runEventloop(ULONG_PTR args) { NetException exception; // Initialize Winsock on Windows #ifdef _WIN32 WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { exception[NetException::Critical] << "runEventloop: WSAStartup failed: " << iResult; throw exception; } // Signal handling for SIGPIPE/SIGINT is different on Windows, keeping POSIX only for POSIX #else signal(SIGINT, signalHandler); signal(SIGPIPE, SIG_IGN); #endif MAINWORKERLOOP: // _pollFD is vestigial from the epoll implementation and is ignored in select. Loading @@ -642,17 +751,21 @@ namespace netplus { pthread_attr_t attr; if (pthread_attr_init(&attr) != 0) { #ifndef _WIN32 exception[NetException::Critical] << "runEventloop: Failed to initialize pthread attributes: " << strerror(errno); throw exception; #endif } // NOTE: THREAD_STACK_SIZE is an external constant. // Uncomment the following block if THREAD_STACK_SIZE is defined in your environment. /* if (pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE) != 0) { #ifndef _WIN32 exception[NetException::Critical] << "runEventloop: Failed to set pthread stack size: " << strerror(errno); pthread_attr_destroy(&attr); throw exception; #endif } */ Loading @@ -665,13 +778,34 @@ namespace netplus { ThreadHelperArgs *helper_args = new ThreadHelperArgs{&eargs, args, i}; pthread_t thread_id; // Use pthread_create with the custom attributes and C-style wrapper int ret = pthread_create(&thread_id, &attr, worker_wrapper, helper_args); int ret = 0; #ifdef _WIN32 // Windows Threading: CreateThread (or _beginthreadex) thread_id = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE)worker_wrapper, // thread function helper_args, // thread argument 0, // default creation flags NULL); // thread id (optional) if (thread_id == NULL) { ret = GetLastError(); } #else // POSIX Threading ret = pthread_create(&thread_id, &attr, worker_wrapper, helper_args); #endif if (ret != 0) { delete helper_args; // Cleanup allocated arguments char errstr[255]; #ifdef _WIN32 strerror_r_netplus(ret, errstr, 255); // Use WinSock-style error wrapper #else strerror_r(ret, errstr, 255); #endif exception[NetException::Critical] << "runEventloop: Failed to create thread: " << errstr; pthread_attr_destroy(&attr); throw exception; Loading