Neal
Neal

Reputation: 41

Is it possible to run a function as a process in rust?

The rust std::process::Command; structure take in a Command::new(program), where program is the path to the program to be executed as shown in the example below.

let output = if cfg!(target_os = "windows") {
    Command::new("cmd")
            .args(&["/C", "echo hello"])
            .output()
            .expect("failed to execute process")

Is it possible to create a new process on windows in rust to run a function?

Upvotes: 4

Views: 2178

Answers (2)

Amjad Orfali
Amjad Orfali

Reputation: 11

Yes you can using the procspawn crate

Upvotes: 0

Anler
Anler

Reputation: 1993

In short, you cannot, creating a new process needs much more information than just the code it will execute. See CreateProcess Windows' system call.

But, you can choose between these alternatives:

  1. Create a thread instead.
  2. Create a process where the executable is the same program that is running but passing a different argument that triggers the execution of the function you are interested in.
  3. Create a Shared Memory Segment.
  4. Create a third library containing your function and share it between your original program and the one you spawn.

Upvotes: 1

Related Questions