Is it possible to use the standard library to spaw

2020-05-07 07:23发布

问题:

This is what I have right now:

Command::new("/path/to/application")
  .args("-param")
  .spawn()

It looks like Rust uses CreateProcessW for running Windows processes, which allows creation flags. Perhaps there is a flag which will do what I need?

回答1:

You could use std::os::windows::process::CommandExt::creation_flags. Please refer to the documentation page for the Process Creation Flags or ideally use the constants from winapi.

You wrote that this is a GUI application, so I assume you don't need the console output on this one. DETACHED_PROCESS does not create conhost.exe, but if you want to process the output you should use CREATE_NO_WINDOW.

I would also recommend using start as the command because otherwise you will have to use cmd.exe and this will probably delay the start by a few milliseconds.

Example

use std::process::Command;
use std::os::windows::process::CommandExt;

const CREATE_NO_WINDOW: u32 = 0x08000000;
const DETACHED_PROCESS: u32 = 0x00000008;

let mut command = Command::new("cmd").args(&["/C", "start", &exe_path]);
command.creation_flags(DETACHED_PROCESS); // Be careful: This only works on windows

// If you use DETACHED_PROCESS you could set stdout, stderr, and stdin to Stdio::null() to avoid possible allocations.


回答2:

std:os::windows::process::CommandExt extends the process::Command builder with Windows-specific options when building for Windows. No constant is defined in the standard library for CREATE_NO_WINDOW, so you'd either need to define it yourself or use the raw value of 0x08000000:

let command = Command::new("my-command")
    .args("param")
    .creation_flags(0x08000000)
    .spawn();


标签: windows rust