diff --git a/ethminer/main.cpp b/ethminer/main.cpp index 508e33b9d6..fc2c189d3f 100644 --- a/ethminer/main.cpp +++ b/ethminer/main.cpp @@ -723,6 +723,12 @@ class MinerCLI // Run CLI in loop while (g_running && mgr.isRunning()) { + + // Wait at the beginning of the loop to give some time + // services to start properly. Otherwise we get a "not-connected" + // message immediately + this_thread::sleep_for(chrono::seconds(m_displayInterval)); + if (mgr.isConnected()) { auto mp = f.miningProgress(m_show_hwmonitors, m_show_power); minelog << mp << f.getSolutionStats() << ' ' << f.farmLaunchedFormatted(); @@ -734,9 +740,16 @@ class MinerCLI else { minelog << "not-connected"; } - this_thread::sleep_for(chrono::seconds(m_displayInterval)); + } +#if API_CORE + + // Stop Api server + api.stop(); + +#endif + mgr.stop(); stop_io_service(); diff --git a/libapicore/ApiServer.cpp b/libapicore/ApiServer.cpp index 31fce1b80b..de4f16cdf1 100644 --- a/libapicore/ApiServer.cpp +++ b/libapicore/ApiServer.cpp @@ -17,17 +17,37 @@ void ApiServer::start() if (m_portnumber == 0) return; m_running.store(true, std::memory_order_relaxed); - m_acceptor.bind(tcp::endpoint(tcp::v4(), m_portnumber)); - cnote << "Api server listening for connections on port " + to_string(m_acceptor.local_endpoint().port()); + tcp::endpoint endpoint(tcp::v4(), m_portnumber); + // Try to bind to port number + // if exception occurs it may be due to the fact that + // requested port is already in use by another service + try + { + m_acceptor.open(endpoint.protocol()); + m_acceptor.bind(endpoint); + m_acceptor.listen(64); + } + catch (const std::exception& _e) + { + cwarn << "Could not start API server on port : " + to_string(m_acceptor.local_endpoint().port()); + cwarn << "Ensure port is not in use by another service"; + return; + } + + cnote << "Api server listening for connections on port " + to_string(m_acceptor.local_endpoint().port()); m_workThread = std::thread{ boost::bind(&ApiServer::begin_accept, this) }; } void ApiServer::stop() { + // Exit if not started + if (!m_running.load(std::memory_order_relaxed)) return; + m_acceptor.cancel(); + m_acceptor.close(); m_running.store(false, std::memory_order_relaxed); // Dispose all sessions (if any) @@ -59,9 +79,10 @@ void ApiServer::handle_accept(std::shared_ptr session, boost::sys } }); + dev::setThreadName("Api"); session->start(); m_sessions.push_back(session); - cnote << "New api session from" << session->socket().remote_endpoint(); + cnote << "New api session from " << session->socket().remote_endpoint(); } else {