Execute a command in rust and wait for n seconds

I am using the following to execute a command and then wait to see if it results in a Segmentation Fault. However sometimes the command that gets executed goes in an infinite loop. I need to put a timeout for 5 seconds so that I am not waiting indefinitely.

    let mut put_command = Command::new(program_name).stdin(Stdio::piped()).spawn().unwrap();
    write!(put_command.stdin.as_mut().unwrap(), "{}", inputtext).unwrap();    
    let one_sec = Duration::from_secs(1);
    let status = put_command.wait().unwrap();
    match status.signal() {
        Some(signal) if signal == libc::SIGSEGV => {
            println!("the process resulted in segmentation fault");
        }
        _ => (),
     
    }

I tried using wait_timeout as following:

        let one_sec = Duration::from_secs(1);
        let status = put_command.wait_timeout(one_sec).unwrap();

but I get the following error during compile time:

error[E0599]: no method named `signal` found for enum `Option` in the current scope
  --> src/main.rs:72:22
   |
72 |         match status.signal() {
   |                      ^^^^^^ method not found in `Option<ExitStatus>`

Please advise.

Here’s the documentation for the trait method I understand you to be using: https://docs.rs/wait-timeout/latest/wait_timeout/trait.ChildExt.html.

That method returns a std::io::Result<Option<ExitStatus>>. So, you need to handle the possibility of an Err in addition to the Ok containing the Option.

Adding a second unwrap call like this would work for now:

let status = put_command.wait_timeout(one_sec).unwrap().unwrap();

But you should of course consider whether panicking is the best way to handle that case, at some point.

status is not of type ExitStatus, it's an Option, you have to handle that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.