kill/
kill.rs

1use std::time::Duration;
2
3use bevy::{prelude::*, time::common_conditions::on_timer};
4use bevy_local_commands::{
5    BevyLocalCommandsPlugin, LocalCommand, Process, ProcessCompleted, ProcessOutput,
6};
7
8fn main() {
9    App::new()
10        .add_plugins((MinimalPlugins, BevyLocalCommandsPlugin))
11        .add_systems(Startup, startup)
12        .add_systems(Update, update)
13        // Kill the command after 2s
14        .add_systems(Update, kill.run_if(on_timer(Duration::from_secs(2))))
15        .run();
16}
17
18fn startup(mut commands: Commands) {
19    // Choose the command based on the OS
20    #[cfg(not(windows))]
21    let cmd = LocalCommand::new("sh").args([
22        "-c",
23        "echo Sleeping for 4s && sleep 4 && echo This should not print or execute && sleep 100",
24    ]);
25    #[cfg(windows)]
26    let cmd = LocalCommand::new("powershell").args([
27        "echo 'Sleeping for 4s'; sleep 4; echo 'This should not print or execute'; sleep 100",
28    ]);
29
30    let id = commands.spawn(cmd).id();
31    println!("Spawned the command as entity {id:?}")
32}
33
34fn kill(mut active_processes: Query<(Entity, &mut Process)>, mut killed: Local<bool>) {
35    if *killed {
36        return;
37    }
38    for (entity, mut process) in active_processes.iter_mut() {
39        println!("Killing {entity:?}");
40        process.kill().unwrap();
41        *killed = true;
42    }
43}
44
45fn update(
46    mut process_output_event: MessageReader<ProcessOutput>,
47    mut process_completed_event: MessageReader<ProcessCompleted>,
48) {
49    for process_output in process_output_event.read() {
50        for line in process_output.lines() {
51            println!("Output Line ({:?}): {line}", process_output.entity);
52        }
53    }
54    if let Some(completed) = process_completed_event.read().last() {
55        println!(
56            "Command {:?} completed (Success - {})",
57            completed.entity,
58            completed.exit_status.success()
59        );
60        // Quit the app
61        std::process::exit(0);
62    }
63}