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.
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");