main.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. extern crate libc;
  2. use core::ffi::{c_char, c_void};
  3. use libc::{mount, umount};
  4. use nix::errno::Errno;
  5. use std::fs;
  6. use std::os::unix::fs::symlink;
  7. use std::path::Path;
  8. fn main() {
  9. mount_test_ramfs();
  10. let target = "/mnt/myramfs/target_file.txt";
  11. let symlink_path = "/mnt/myramfs/another/symlink_file.txt";
  12. let dir = "/mnt/myramfs/another";
  13. fs::write(target, "This is the content of the target file.")
  14. .expect("Failed to create target file");
  15. fs::create_dir(dir).expect("Failed to create target dir");
  16. assert!(Path::new(target).exists(), "Target file was not created");
  17. assert!(Path::new(dir).exists(), "Target dir was not created");
  18. symlink(target, symlink_path).expect("Failed to create symlink");
  19. assert!(Path::new(symlink_path).exists(), "Symlink was not created");
  20. let symlink_content = fs::read_link(symlink_path).expect("Failed to read symlink");
  21. assert_eq!(
  22. symlink_content.display().to_string(),
  23. target,
  24. "Symlink points to the wrong target"
  25. );
  26. fs::remove_file(symlink_path).expect("Failed to remove symlink");
  27. fs::remove_file(target).expect("Failed to remove target file");
  28. fs::remove_dir(dir).expect("Failed to remove test_dir");
  29. assert!(!Path::new(symlink_path).exists(), "Symlink was not deleted");
  30. assert!(!Path::new(target).exists(), "Target file was not deleted");
  31. assert!(!Path::new(dir).exists(), "Directory was not deleted");
  32. umount_test_ramfs();
  33. println!("All tests passed!");
  34. }
  35. fn mount_test_ramfs() {
  36. let path = Path::new("mnt/myramfs");
  37. let dir = fs::create_dir_all(path);
  38. assert!(dir.is_ok(), "mkdir /mnt/myramfs failed");
  39. let source = b"\0".as_ptr() as *const c_char;
  40. let target = b"/mnt/myramfs\0".as_ptr() as *const c_char;
  41. let fstype = b"ramfs\0".as_ptr() as *const c_char;
  42. // let flags = MS_BIND;
  43. let flags = 0;
  44. let data = std::ptr::null() as *const c_void;
  45. let result = unsafe { mount(source, target, fstype, flags, data) };
  46. assert_eq!(
  47. result,
  48. 0,
  49. "Mount myramfs failed, errno: {}",
  50. Errno::last().desc()
  51. );
  52. println!("Mount myramfs success!");
  53. }
  54. fn umount_test_ramfs() {
  55. let path = b"/mnt/myramfs\0".as_ptr() as *const c_char;
  56. let result = unsafe { umount(path) };
  57. if result != 0 {
  58. let err = Errno::last();
  59. println!("Errno: {}", err);
  60. println!("Infomation: {}", err.desc());
  61. }
  62. assert_eq!(result, 0, "Umount myramfs failed");
  63. }