Search code examples
rustrust-tokio

How to compile a a project that use tokio::signal::unix on Windows?


How to compile a project that's using tokio::signal::unix on Windows? Whenever I try to compile a project with tokio::signal::unix, it will show this error.

58 | use tokio::signal::unix::SignalKind;
   |                    ^^^^ could not find `unix` in `signal`

Or is there a better way to handle signal with no regard to the operating system?

Is there's any way to make the code base useable regardless of the platform?


Solution

  • OS signal are specific to each operating system, so you cannot use Unix signals on Windows. The only cross platform signal tokio supports is ctrl-c but if you want to support both platforms then you can use cfg to select the platform specific import

    #[cfg(unix)]
    use tokio::signal::unix;
    #[cfg(windows)]
    use tokio::signal::windows;
    

    and then in your code, use the library for that platform

    #[cfg(unix)]
    println!("On Unix"); // Only runs on Unix/Linux
    #[cfg(windows)]
    println!("On Windows"); // Only runs on Windows
    

    All the Unix specific signals can be found here and the Windows specific here