본문 바로가기

Rust/기타 팁

std::process::Command 관련

[1. 개요]

rust 에서 윈도우/리눅스 명령어를 사용하고, 그 결과 등을 캡쳐 할 필요가 있을 때

std::process::Command 를 사용하여 원하는 작업을 할 수 있다.

 

여기서는 ssh2 에서 처럼 작업을 수행하고,

블로킹 되는 것 없이, 현재 진행 중인 작업 중인 로그를 출력하고,

자식 프로세스의 Exit code 를 받아오도록 한다.


[2. 예제]

#[cfg(test)]
mod tests {
use std::io::Read;
use std::process::Command;
#[test]
fn cmd_test() {
println!("Start command");
let mut out = Command::new("cmd")
.args(["/C", "echo hello && ping -n 5 127.0.0.1 && echo end_command && exit /b 99"])
// 자식 프로세스의 표준 출력을 부모 프로세스로 연결
.stdout(std::process::Stdio::piped())
// 자식 프로세스를 실행 => 멀티 프로세스가 된다.
.spawn()
.unwrap();
println!("After spawn");
// let mut t = out.stdout.unwrap();
let mut t = out.stdout.take().unwrap();
println!("======================");
loop {
let mut buf: [u8; 1024] = [0; 1024];
let read_bytes = t.read(&mut buf).unwrap();
if read_bytes == 0 {
break;
}
println!("Read bytes: {}", read_bytes);
// 작업 환경에 따라, 문자열이 깨질 수 있다.
// 읽어 들인 버퍼를 인코딩 하는 방법은 추후 정리하도록 한다.
println!("{}", String::from_utf8_lossy(&mut buf));
}
let exit_status = out.wait().unwrap();
println!("Exit code : {}", exit_status.code().unwrap());
}
}
view raw command.rs hosted with ❤ by GitHub

[3. 참조]

'Rust > 기타 팁' 카테고리의 다른 글