Rust中process::Command无法运行指定程序的问题求助
Rust调用外部程序无反应的问题修复
你这段代码的核心问题是:只创建了Command命令对象,但没有触发执行操作。Command::new()只是初始化了命令的配置,必须调用执行方法才能真正启动外部程序。
修改后的代码
use std::process::Command; use std::path::Path; use std::env; const ROM_DIRECTORY: &str = "C:/ROMS"; fn main() { let internal_directory = Path::new(ROM_DIRECTORY); assert!(env::set_current_dir(internal_directory).is_ok()); println!("Successfully changed working directory to {}!", internal_directory.display()); // 关键:添加spawn()或status()方法执行命令 Command::new("Rockman.nes") .spawn() // 非阻塞启动程序,立即返回子进程句柄 .expect("Failed to launch Rockman.nes"); }
两种执行方法的区别
spawn():非阻塞模式,程序启动后当前Rust进程会继续执行后续代码(如果有的话)status():阻塞模式,当前Rust进程会等待外部程序退出后才继续执行,适合需要等待程序结束的场景
另外需要注意:如果系统无法直接识别.nes文件的默认打开程序,可能需要指定模拟器路径,比如:
Command::new("path/to/your/nes/emulator.exe") .arg("Rockman.nes") .spawn() .expect("Failed to launch emulator");
内容的提问来源于stack exchange,提问作者Railu
相关产品推荐
相关产品推荐

