How would I check if a process such as "example.exe" is currently running using the rust programming language.
You can use sysinfo crate, or particularly processes_by_name
You can get iterator to processes containing the name using the function
fn processes_by_name<'a>(&'a self, name: &'a str) -> Box<dyn Iterator<Item = &'a Process> + 'a>
You can use it like this
use sysinfo::{ProcessExt, System, SystemExt};
let s = System::new_all();
for process in s.processes_by_name("htop") {
//check here if this is your process
}
UPDATE: New version (0.23.0) also contains processes_by_exact_name
It returns an iterator to processes with the exact given name
You can use it like this
use sysinfo::{ProcessExt, System, SystemExt};
let s = System::new_all();
for process in s.processes_by_exact_name("htop") {
//Your code goes here
}
Related
A similar question I posted earlier is here
Rust can't modify RefCell in Rc, but completely different.
I want to simulate some natural process, so I have a Simulator, and a reactor like a NuclearReactor. The simulator will modify the reactor, and the reactor can reversely influance the simulator by modifying it. One important thing is that the NuclearReactor is wrapped from somewhere else, the solid_function must has a inmutable &self.
So after reading rust book of RefCell, I wrote something like these, It complies, but crashed.
use std::borrow::BorrowMut;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
pub struct Simulator {
nr: NuclearReactor,
data: Vec<f64>,
}
impl Simulator {
pub fn on_nuclear_data(&mut self, x: i64) {
// modify self
}
pub fn run_simulation(&mut self) {
self.nr.write_simulator();
}
}
pub struct NuclearReactor {
simulator: Option<Weak<RefCell<Simulator>>>,
}
impl NuclearReactor {
pub fn solid_function(&self, x: i64) {
/*
this function `&self` is solid, so I have to use a RefCell to wrap Simulator
*/
}
pub fn write_simulator(&self) {
/*
thread 'main' panicked at 'already borrowed: BorrowMutError'
*/
(*self.simulator.as_ref().unwrap().upgrade().unwrap()).borrow_mut().on_nuclear_data(0);
}
}
pub fn main() {
let nr_ = NuclearReactor {
simulator: None
};
let mut sm_ = Rc::new(RefCell::new(Simulator {
nr: nr_,
data: vec![],
}));
(*sm_).borrow_mut().nr.simulator = Some(Rc::downgrade(&sm_));
(*sm_).borrow_mut().run_simulation();
}
Obviously, the runtime check of borrow_mut fails.
Actually the NuclearReactor is my online code, the Simulator is an offline test, so I wanna modify the NuclearReactor at a minimal cost to let it run on the offline environment. That's why I have to keep the function solid_function with an immutable &self. Changing it to a &mut self is and then move to-modifying objects to a seperate function is feasible, but then I have to modify the online code frequently at a high cost. It there anything cool that can solve it ?
Ok, after reading this: http://smallcultfollowing.com/babysteps/blog/2018/11/01/after-nll-interprocedural-conflicts/
I finnaly realized that what I am doing is something like below and rust was helping me avoiding bugs.
let v: Vec<i64> = vec![1,2,3];
for ele in v.iter_mut(){
v.push(1);
}
Thankfully, pushing NuclearReactor's modify to a temp buffer then apply them to Simulator is just enough to solve my problem.
Also, I didn't explain the question clearly (actually I didn't get the point to describe the question until I solved it), so the community can't help me.
I am trying to run multiple functions on different threads. I wrote this (minimal) code that works
use std::thread;
fn f1(count: usize) {
for i in 0..count { /*do something*/ }
}
fn f2(count: usize) {
for i in 0..count { /*do something*/ }
}
fn run(ops: &Vec<impl Fn(usize) + Sync + Send + Copy + 'static>) {
for i in 0..ops.len() {
let func = ops[i];
thread::spawn(move || func(1000));
}
}
fn main() {
let ops = vec![f1, f1]; // putting the same function twice
run(&ops);
}
However, as soon as I send different functions
let ops = vec![f1, f2];
Compiling fails. As I understand it, I cannot hold different types in the same vector (I guess, functions have different memory requirements, though I'm not quite sure how function pointers work).
I tried browsing similar questions on SO, and I tried this solution
let ops: Vec<&dyn Fn(usize)> = vec![&f1, &f2];
and I get this error
`dyn Fn(usize)` cannot be shared between threads safely
the trait `Sync` is not implemented for `dyn Fn(usize)`
And I'm stuck as I'm struggling to understand the base issue. Do you have insights on how I should understand this problem, and any pointers on how to solve it ?
Thank you!
Just as you can add the Sync marker with impl, you can also add it with &dyn, but you may need parenthesis to disambiguate:
fn run(ops: &Vec<&'static (dyn Fn(usize) + Sync)>)
Two minor comments:
Generally, using &[…] instead of &Vec<…> is more flexible and to be preferred.
No need to do for i in 0…foos.len() in rust, for foo in foos will do fine. (You may occasionally have to use for foo in &foos or for foo in foos.iter(). If you do need the index, .enumerate() is convenient.)
If the 'static is a bother (e.g. because you want to pass in some closure that captures local variables and can't be 'static), you could either use scoped threads (example), or pass owned Fns as Vec<Box<dyn Fn(usize) + Sync>>.
I know, the answers for similar questions already exist... kinda... all that I found were very high level instructions rather than code examples and I couldn't really follow them and I've been stuck in place for days now...
I need to share a variable with a closure. So I have my MockSlave struct. I want it to create a vector that can then be shared with the shell closure. The current version looks something like this
impl MockSlave {
pub async fn new(port: i32) -> Result<Self, Box<dyn std::error::Error>> {
let addr = String::from(format!("https://127.0.0.1:{}", port).as_str());
let endpoint = Endpoint::from_str(addr.as_str())?;
let commands = Rc::new(RefCell::new(Vec::new()));
let client = SlaveClient::new(endpoint, CommandProcessors {
shell: Some(|command| {
commands.borrow_mut().push(command);
Ok(())
})
}).await?;
Ok(MockSlave {
client,
commands
})
}
For clarity, here's SlaveClient::new
pub async fn new(endpoint: Endpoint, processors: CommandProcessors) -> Result<Self, tonic::transport::Error> {
let slave = SlaveClient {
client: SlaveManagerClient::connect(endpoint).await?,
processors
};
Ok(slave)
}
And here's CommandProcessors:
pub struct ReadWriteStreamingCommand {
pub command: Command
}
pub type ReadWriteSteamingCommandprocessor = fn(Box<ReadWriteStreamingCommand>) -> Result<(), Box<dyn Error>>;
pub struct CommandProcessors {
pub shell: Option<ReadWriteSteamingCommandprocessor>
}
Now, the fun part is that VSCode and cargo build give me slightly different errors about the same thing.
VSCode says:
closures can only be coerced to `fn` types if they do not capture any variables
Meanwhile, cargo build says
error[E0308]: mismatched types
--> tests/api_tests/src/mock_slave.rs:20:25
|
20 | shell: Some(|command| {
| _________________________^
21 | | commands.borrow_mut().push(command);
22 | | Ok(())
23 | | })
| |_____________^ expected fn pointer, found closure
Please help. This is at least my 10th approach to this problem over the course of a week. I am not going to move forward by myself...
fn(Box<ReadWriteStreamingCommand>) -> Result<(), Box<dyn Error>>;
This is not the type you think it is. This is the type of pointers to functions that exist statically in your code. That is, functions defined at the top-level or closures which don't actually close over any variables. To accept general Rust callables (including traditional functions and closures), you need one of Fn, FnMut, or FnOnce.
I can't tell from the small code you've shown which of the three you need, but the basic idea is this.
Use FnOnce if you are only going to call the function at most once. This is useful if you're writing some kind of "control flow" type of construct or mapping on the inside of an Option (where at most one value exists).
Use FnMut if you are going to call the function several times but never concurrently. This is what's used by most Rust built-in collection functions like map and filter, since it's always called in a single thread. This is the one I find myself using the most often for general-purpose things.
Use Fn if you need concurrent access and are planning to share across threads.
Every Fn is an FnMut (any function that can be called concurrently can be called sequentially), and every FnMut is an FnOnce (any function that can be called can obviously be called once), so you should choose the highest one on the list above that you can handle.
I'll assume you want FnMut. If you decide one of the others is better, the syntax is the same, but you'll just need to change the name. The type you want, then, is
dyn FnMut(Box<ReadWriteStreamingCommand>) -> Result<(), Box<dyn Error>>
But this is a trait object and hence is not Sized, so you can't do much with it. In particular, you definitely can't put it in another Sized data structure. Instead, we'll wrap it in a Box.
pub type ReadWriteSteamingCommandprocessor = Box<dyn FnMut(Box<ReadWriteStreamingCommand>) -> Result<(), Box<dyn Error>>>;
And then
shell: Some(Box::new(|command| {
commands.borrow_mut().push(command);
Ok(())
}))
I would like to write a simulation algorithm in Rust that has three main parts. The first part is a struct that maintains the current state of the system and associated methods to make allowed state transitions. The second part is a simulation strategy, this tells which state transition(s) to make next (e.g. I will have a slow but accurate simulation strategy and a quick but approximate strategy). Finally, I have a way to serialise the system after a simulation step was taken (e.g. one method writes the system to csv while another one to json).
I would like to choose both the simulation strategy and the serialisation method at run time.
Coming from Python, my first try for the main simulation loop looked like this:
let mut system = System { ... };
let simulator = GillespieAlgorithm { system: &mut system, ... }; // this will be dynamic eventually
let output_formatter = CSVFormatter { system: &system, ... }; // this will be dynamic eventually
output_formatter.start();
for _ in 1..100 {
simulator.step();
output_formatter.write_current_state();
}
output_formatter.stop();
Of course, this doesn't work because I want to borrow system twice with one of them being a mutable reference.
What would be the idiomatic Rust solution to this problem? My understanding is that I should somehow attach a behaviour dynamically to System instead of passing system to other structs.
You've mentioned in the comments, that you want to keep the &mut system in your simulation. Thats fine and you can still use system, as long as you're getting it via the GillespieAlgorithm. If you're fine to pass it to the formatter by method argument rather than constructor, this might be a solution for you (playground)
struct System();
struct GillespieAlgorithm<'a> { system: &'a mut System }
struct CSVFormatter();
fn main() {
let mut system = System();
let mut simulator : Box<dyn Algorithm> = Box::new(GillespieAlgorithm { system: &mut system }); // this will be dynamic eventually
let output_formatter: Box<dyn Formatter> = Box::new(CSVFormatter());
output_formatter.start();
for _ in 1..100 {
simulator.step();
output_formatter.write_current_state(simulator.borrow_system());
}
output_formatter.stop();
}
trait Algorithm {
fn step(&mut self) {}
fn borrow_system(&self) -> &System;
}
impl<'a> Algorithm for GillespieAlgorithm<'a> {
fn step(&mut self) {}
fn borrow_system(&self) -> &System {
self.system
}
}
trait Formatter {
fn start(&self);
fn write_current_state(&self, system: &System);
fn stop(&self);
}
impl Formatter for CSVFormatter {
fn start(&self) {}
fn write_current_state(&self, _system: &System) {}
fn stop(&self) {}
}
If you don't need the entire System in the CSVFormatter, you could also return a dedicated state struct in step() and pass this to your formatter.
After reading these std::thread::Builder and std::thread::spawn I understand their differences (more or less), but is it recommended to use always std::thread::Builder?.
I do not understand why there are two; can someone explain to me when is best to use one or the other? Perhaps one or the other cannot or should not be used in some cases?
let child: std::thread::JoinHandle<()> = std::thread::spawn(move || {
for a in 0..100{
println!("D");
std::thread::sleep(std::time::Duration::from_millis(50));
}
});
child.join();
let child: Result<std::thread::JoinHandle<()>,_> = std::thread::Builder::new().name("child1".to_string()).spawn(move || {
for a in 0..100{
println!("D");
std::thread::sleep(std::time::Duration::from_millis(50));
}
});
child.unwrap().join();
The documentation for thread::Builder answers all of your questions by listing all the functions and types that don't directly correspond to thread::spawn:
fn name(self, name: String) -> Builder
Names the thread-to-be. Currently the name is used for identification
only in panic messages.
fn stack_size(self, size: usize) -> Builder
Sets the size of the stack for the new thread.
fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
...
Unlike the spawn free function, this method yields an io::Result to
capture any failure to create the thread at the OS level.
So a thread::Builder allows you to:
Set a thread name.
Set the stack size.
Handle an error to start the thread.
Use thread::spawn when you don't care about any of those.