From 11b9897f883d9cde3ae173b191cf6b95e18fc602 Mon Sep 17 00:00:00 2001 From: Benau Date: Fri, 6 Dec 2019 11:58:51 +0800 Subject: [PATCH] Add non-blocking thread network console for linux --- src/network/network_console.cpp | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/network/network_console.cpp b/src/network/network_console.cpp index 120d8d7e0..57cab545c 100644 --- a/src/network/network_console.cpp +++ b/src/network/network_console.cpp @@ -29,8 +29,17 @@ #include #include +#ifndef WIN32 +# include +# include +# include +#endif + namespace NetworkConsole { +#ifndef WIN32 +std::string g_cmd_buffer; +#endif // ---------------------------------------------------------------------------- void showHelp() { @@ -45,16 +54,61 @@ void showHelp() std::cout << "speedstats, Show upload and download speed." << std::endl; } // showHelp +// ---------------------------------------------------------------------------- +#ifndef WIN32 +bool pollCommand() +{ + struct timeval timeout; + fd_set rfds; + int fd; + char c; + + // stdin file descriptor is 0 + fd = 0; + timeout.tv_sec = 0; + timeout.tv_usec = 10000; + + FD_ZERO(&rfds); + FD_SET(fd, &rfds); + + if (select(fd + 1, &rfds, NULL, NULL, &timeout) <= 0) + return false; + if (read(fd, &c, 1) != 1) + return false; + + if (c == '\n') + return true; + g_cmd_buffer += c; + return false; +} // pollCommand +#endif + // ---------------------------------------------------------------------------- void mainLoop(STKHost* host) { VS::setThreadName("NetworkConsole"); + +#ifndef WIN32 + g_cmd_buffer.clear(); +#endif + showHelp(); std::string str = ""; while (!host->requestedShutdown()) { +#ifndef WIN32 + if (!pollCommand()) + continue; + + std::stringstream ss(g_cmd_buffer); + if (g_cmd_buffer.empty()) + continue; + g_cmd_buffer.clear(); +#else getline(std::cin, str); std::stringstream ss(str); +#endif + int number = -1; ss >> str >> number; if (str == "help")