Skip to content

Commit 493ae3e

Browse files
committed
ch6: fix fd in fork
1 parent 02e022f commit 493ae3e

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

os/src/fs/inode.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,17 @@ impl OSInode {
6262
}
6363

6464
pub fn copy(&self) -> Self {
65-
Self::new(self.readable, self.writable, self.clone_inner_inode())
65+
let inner = self.inner.exclusive_access();
66+
Self {
67+
readable: self.readable,
68+
writable: self.writable,
69+
inner: unsafe {
70+
UPSafeCell::new(OSInodeInner {
71+
offset: inner.offset,
72+
inode: inner.inode.clone(),
73+
})
74+
},
75+
}
6676
}
6777
}
6878

user/src/bin/filetest.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#![no_std]
2+
#![no_main]
3+
4+
use user_lib::{close, exit, fork, open, read, waitpid, write, OpenFlags};
5+
6+
#[macro_use]
7+
extern crate user_lib;
8+
9+
#[no_mangle]
10+
pub fn main() -> i32 {
11+
let test_str = b"Hello, world!";
12+
let fname = "fname\0";
13+
let fd = open(fname, OpenFlags::CREATE | OpenFlags::WRONLY);
14+
assert!(fd > 0);
15+
let fd = fd as usize;
16+
write(fd, &test_str[..]);
17+
close(fd);
18+
19+
let fd = open(fname, OpenFlags::RDONLY);
20+
assert!(fd > 0);
21+
let fd = fd as usize;
22+
let mut buffer = [0u8; 4];
23+
let read_len = read(fd, &mut buffer) as usize;
24+
println!(
25+
"main 1st read: {}",
26+
core::str::from_utf8(&buffer[..read_len]).unwrap()
27+
); // should be "Hell"
28+
assert_eq!(&buffer[..read_len], &test_str[..read_len]);
29+
30+
let pid = fork();
31+
if pid == 0 {
32+
buffer.fill(0);
33+
let n = read(fd, &mut buffer) as usize;
34+
println!(
35+
"child read: {}",
36+
core::str::from_utf8(&buffer[..n]).unwrap()
37+
); // should be "o, w", coz inherit file cursor(offset)
38+
assert_eq!(&buffer[..n], &test_str[read_len..read_len + n]);
39+
close(fd);
40+
exit(0);
41+
} else {
42+
let mut exit_code = 0;
43+
waitpid(pid as usize, &mut exit_code);
44+
45+
buffer.fill(0);
46+
let n = read(fd, &mut buffer) as usize;
47+
println!(
48+
"main 2nd read: {}",
49+
core::str::from_utf8(&buffer[..n]).unwrap()
50+
); // should be also "o, w", coz file cursor(offset) independent
51+
assert_eq!(&buffer[..n], &test_str[read_len..read_len + n]);
52+
}
53+
0
54+
}

0 commit comments

Comments
 (0)