I'm seeing some behavior I can't explain when I use a RwLock and fork. Basically the child process reports a RwLock as still acquired, while the parent doesn't, even though they both run the same code path. My understanding is that the child process should receive an independent copy of the parent process's memory space, locks included, so it doesn't make sense that they should report different results.
The expected behavior is that the child and parent both report "mutex held: false". Interestingly, this works as expected when a Mutex is used, instead of a RwLock.
use libc::fork;
use std::error::Error;
use std::sync::RwLock;
fn main() -> Result<(), Box<dyn Error>> {
let lock = RwLock::new(());
let guard = lock.write();
let res = unsafe { fork() };
drop(guard);
match res {
0 => {
let held = lock.try_write().is_err();
println!("CHILD mutex held: {}", held);
}
_child_pid => {
let held = lock.try_write().is_err();
println!("PARENT mutex held: {}", held);
}
}
Ok(())
}
Output:
PARENT mutex held: false
CHILD mutex held: true