diff --git a/src/main.rs b/src/main.rs index de06b38..7456f8b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -288,7 +288,7 @@ pub enum SubCmd { }, } -#[tokio::main] +#[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { color_eyre::install()?; let args = Cmd::parse(); diff --git a/src/service.rs b/src/service.rs index 745cc56..c2c0fe4 100644 --- a/src/service.rs +++ b/src/service.rs @@ -14,12 +14,13 @@ use service_manager::{ ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStopCtx, ServiceUninstallCtx, }; -use std::ffi::OsString; use std::net::SocketAddr; #[cfg(feature = "tcp")] use std::net::TcpListener as SocketBinder; #[cfg(not(feature = "tcp"))] use std::net::UdpSocket as SocketBinder; +use std::time::Duration; +use std::{ffi::OsString, thread::sleep}; use std::path::PathBuf; use sysinfo::{Pid, System, SystemExt}; @@ -163,7 +164,14 @@ impl ServiceControl for NodeServiceManager { fn get_available_port(&self) -> Result { let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - Ok(SocketBinder::bind(addr)?.local_addr()?.port()) + let socket = SocketBinder::bind(addr)?; + let port = socket.local_addr()?.port(); + drop(socket); + // Sleep a little while to make sure that we've dropped the socket. + // Without the delay, we may face 'Port already in use' error, when trying to re-use this port. + sleep(Duration::from_secs(1)); + + Ok(port) } fn install(&self, config: ServiceConfig) -> Result<()> {