Skip to main content

exec/
exec.rs

1// Copyright (c) 2024 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5fn call_ls() {
6    println!("[ls] pid: {}", unsafe { nc::getpid() });
7    let args = ["ls", "-l", "-a"];
8    let env = ["DISPLAY=wayland"];
9    let ret = unsafe { nc::execve("/bin/ls", &args, &env) };
10    assert!(ret.is_ok());
11}
12
13fn call_date() {
14    println!("[date] pid: {}", unsafe { nc::getpid() });
15    let args = ["date", "+%Y:%m:%d %H:%M:%S"];
16    let env = ["DISPLAY=:0"];
17    let ret = unsafe { nc::execveat(nc::AT_FDCWD, "/bin/date", &args, &env, 0) };
18    assert!(ret.is_ok());
19}
20
21fn call_id() {
22    let ret = unsafe { nc::openat(nc::AT_FDCWD, "/usr/bin/id", nc::O_RDONLY | nc::O_CLOEXEC, 0) };
23    assert!(ret.is_ok());
24    let fd = ret.unwrap();
25    let args = ["id", "-u", "-n"];
26    let env = ["DISPLAY=:0"];
27    let ret = unsafe { nc::execveat(fd, "", &args, &env, nc::AT_EMPTY_PATH) };
28    assert!(ret.is_ok());
29}
30
31fn main() {
32    let pid = unsafe { nc::fork() };
33    match pid {
34        Err(errno) => eprintln!("Failed to call fork(), err: {errno}"),
35        Ok(0) => {
36            // Child process
37            call_ls();
38        }
39        Ok(child_pid) => {
40            // Parent process
41            println!("[main] child pid is: {child_pid}");
42        }
43    }
44
45    let pid = unsafe { nc::fork() };
46    match pid {
47        Err(errno) => eprintln!("Failed to call fork(), err: {errno}"),
48        Ok(0) => {
49            // Child process
50            call_date();
51        }
52        Ok(child_pid) => {
53            // Parent process
54            println!("[main] child pid is: {child_pid}");
55        }
56    }
57
58    let pid = unsafe { nc::fork() };
59    match pid {
60        Err(errno) => eprintln!("Failed to call fork(), err: {errno}"),
61        Ok(0) => {
62            // Child process
63            call_id();
64        }
65        Ok(child_pid) => {
66            // Parent process
67            println!("[main] child pid is: {child_pid}");
68        }
69    }
70
71    // Wait for a while.
72    let ts = nc::timespec_t {
73        tv_sec: 2,
74        tv_nsec: 0,
75    };
76    unsafe {
77        let _ret = nc::nanosleep(&ts, None);
78    }
79}