Tokio 0.2 and daemonize process

Hello. I have a problem with daemonizing process. If I run program as daemon, Tokio TCP server is dead.
How to fix it?

tokio = { version = "0.2.20", features = ["full"] }
daemonize = "0.4.1"

Could you add some code please?

/// any code .....
      if matches.is_present("daemon")
        {
            let stdout = File::create(format!("{}/daemon.out", working_directory))?;
            let stderr = File::create(format!("{}/daemon.err", working_directory))?;

            let daemon = Daemonize::new()
                .pid_file(&pid_file_name) // Every method except `new` and `start`
                .chown_pid_file(true)      // is optional, see `Daemonize` documentation
                .working_directory(&working_directory) // for default behaviour.
                .user("root")
                .group("root") // Group name
                .group(2)        // or group id.
                .umask(0o777)    // Set umask, `0o027` by default.
                .stdout(stdout)  // Redirect stdout to `/tmp/daemon.out`.
                .stderr(stderr);  // Redirect stderr to `/tmp/daemon.err`.

            let res = daemon.start();
            match res
            {
                Ok(_) => { info!("STARTED AS A DAEMON"); },
                Err(e) =>{
                    error!("{}", e);
                }
            };
        }

    let mut listener = tokio::net::TcpListener::bind(connection_string).await?;

    loop
        {
            let (stream, client_address) = listener.accept().await?;

            stream.set_nodelay(true).expect("Cannot set no delay option.");
            stream.set_keepalive(Some(TCP_KEEP_ALIVE_DURATION)).expect("Cannot set keep alive option.");

            let remote = client_address.to_string();
            let port_name_cloned  = port_name.clone();

            let sp_tcp_client_mutex = Arc::clone(&serial_port_mutex);

            let diag_mutex = Arc::clone(&diag_mutex);

            tokio::spawn(async move {
                match process(&diag_mutex, stream, sp_tcp_client_mutex, &gateway_type, &remote, &port_name_cloned).await
                {
                    Err(e) => {
                        error!("Remote: {}. Mode: {}. {}", &client_address.to_string(), &gateway_type.as_str(), e);
                    },
                    Ok(()) => {
                        warn!("Client disconnected. Remote: {}. Mode: {}", &client_address.to_string(), &gateway_type.as_str());
                    }
                };
            });
        }

You must create the Tokio runtime after daemonizing it. The Tokio runtime can't survive a fork.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.