Skip to content

Commit

Permalink
examples: Add exec
Browse files Browse the repository at this point in the history
Related: #22
  • Loading branch information
XuShaohua committed Jul 31, 2024
1 parent f422e0a commit ade054e
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions examples/exec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

fn call_ls() {
println!("[ls] pid: {}", unsafe { nc::getpid() });
let args = ["ls", "-l", "-a"];
let env = ["DISPLAY=wayland"];
let ret = unsafe { nc::execve("/bin/ls", &args, &env) };
assert!(ret.is_ok());
}

fn call_date() {
println!("[date] pid: {}", unsafe { nc::getpid() });
let args = ["date", "+%Y:%m:%d %H:%M:%S"];
let env = [];
let ret = unsafe { nc::execve("/bin/date", &args, &env) };
assert!(ret.is_ok());
}

fn main() {
let pid = unsafe { nc::fork() };
match pid {
Err(errno) => eprintln!("Failed to call fork(), err: {errno}"),
Ok(0) => {
// Child process
call_ls();
}
Ok(child_pid) => {
// Parent process
println!("[main] child pid is: {child_pid}");
}
}

let pid = unsafe { nc::fork() };
match pid {
Err(errno) => eprintln!("Failed to call fork(), err: {errno}"),
Ok(0) => {
// Child process
call_date();
}
Ok(child_pid) => {
// Parent process
println!("[main] child pid is: {child_pid}");
}
}

// Wait for a while.
let ts = nc::timespec_t {
tv_sec: 2,
tv_nsec: 0,
};
unsafe {
let _ret = nc::nanosleep(&ts, None);
}
}

0 comments on commit ade054e

Please sign in to comment.