https://cloud.tencent.com/developer/article/1620862
// use std::thread; // fn main() { // let child = thread::spawn(move || { // println!("Hello, I am a new rust thread!"); // }); // let res = child.join(); // println!("{:?}", res); // println!("Hello, I am main thread!"); // } fn main() { unsafe { let pid = libc::fork(); if pid > 0 { println!("Hello, I am parent thread: {}", libc::getpid()); } else if pid == 0 { println!("Hello, I am child thread: {}", libc::getpid()); println!("My parent thread: {}", libc::getppid()); } else { println!("Fork creation failed!"); } } }
Compiling hello_world v0.1.0 (/data2/rust/libctest) error[E0433]: failed to resolve: use of undeclared type or module `libc` --> src/main.rs:17:19 | 17 | let pid = libc::fork(); | ^^^^ use of undeclared type or module `libc` error[E0433]: failed to resolve: use of undeclared type or module `libc` --> src/main.rs:20:55 | 20 | println!("Hello, I am parent thread: {}", libc::getpid()); | ^^^^ use of undeclared type or module `libc` error[E0433]: failed to resolve: use of undeclared type or module `libc` --> src/main.rs:23:54 | 23 | println!("Hello, I am child thread: {}", libc::getpid()); | ^^^^ use of undeclared type or module `libc` error[E0433]: failed to resolve: use of undeclared type or module `libc` --> src/main.rs:24:46 | 24 | println!("My parent thread: {}", libc::getppid()); | ^^^^ use of undeclared type or module `libc` error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0433`. error: could not compile `hello_world`. To learn more, run the command again with --verbose.
libc 的导入 在项目的 Cargo.toml 中添加如下配置,就可以导入 libc 了。 [dependencies] libc = "0.2"
[root@bogon libctest]# cargo build Updating crates.io index Compiling libc v0.2.81 Compiling hello_world v0.1.0 (/data2/rust/libctest) Finished dev [unoptimized + debuginfo] target(s) in 31.73s [root@bogon libctest]# cargo runc error: no such subcommand: `runc` Did you mean `run`? [root@bogon libctest]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` Hello, I am child thread: 1444 My parent thread: 1437 Hello, I am parent thread: 1437 [root@bogon libctest]#