How to make process::Command::new() to execute inner Rust function

Hello,

Idk even if it's possible but looking at Command's src code I assume it is.

I want to make Command::new() execute an internally defined function.

for example like this:

pub fn try_me() {}

pub fn main() {
    let mut proc = process::Command::new("try_me");
}

is there a way how I have to define try_me function and/or how I pass it to the Command::new?

thanks

That's not what Command does – it is for running programs other than your own. Why don't you just call the function?

So basically I want to take input from a user and spawn a separate process that executes it. But the user input can be a Linux executable command (like ls or pwd) or it can be a custom function defined internally.

The lengthy solution will be to check if the input is a Linux executable of a custom function and act accordingly. But I thought, maybe there's a better way

Do you need to run the custom function in a new process? Perhaps a new thread would be enough?

If you're writing a shell that can execute either builtin commands or other executables, I think the usual way to handle it is to match the input against a known list of builtin names and only treat it as a Command if none of them fit, like this:

match get_command_from_user() {
    "shopt" => do_shopt(),
    "fg" => do_fg(),
    "bg" => do_bg(),
    // ...
    other => Command::new(other).args(get_args_from_user()).spawn().unwrap(),
}

which is about what I'd recommend. This approach executes builtin commands in-process.

Yes, that's how I have rn. But then I ran into a trouble when I want to redirect the output of the custom function into a different stdout

You could have the custom function take an additional argument that describes where to send its stdout.

1 Like

To answer directly what you want to do: you'd have to write a whole new Rust program that runs try_me in its main.

cargo new --bin try_me

compile this, and make the result available in PATH.

But that's a very cumbersome and inefficient way of doing it. You should just call the function directly.

If you want that function to output somewhere else than stdout, write it so! Don't use println!, but use write!(that_other_place macro instead. See std::io::Write or std::fmt::Write traits.

use std::io::Write;
write!(std::io::stderr().lock(), "this writes to stderr");
1 Like

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.