《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.4 KiB

12 years ago
12 years ago
12 years ago
12 years ago
  1. #include <defs.h>
  2. #include <kmalloc.h>
  3. #include <sem.h>
  4. #include <vfs.h>
  5. #include <dev.h>
  6. #include <file.h>
  7. #include <sfs.h>
  8. #include <inode.h>
  9. #include <assert.h>
  10. //called when init_main proc start
  11. void
  12. fs_init(void) {
  13. vfs_init();
  14. dev_init();
  15. sfs_init();
  16. }
  17. void
  18. fs_cleanup(void) {
  19. vfs_cleanup();
  20. }
  21. void
  22. lock_files(struct files_struct *filesp) {
  23. down(&(filesp->files_sem));
  24. }
  25. void
  26. unlock_files(struct files_struct *filesp) {
  27. up(&(filesp->files_sem));
  28. }
  29. //Called when a new proc init
  30. struct files_struct *
  31. files_create(void) {
  32. //cprintf("[files_create]\n");
  33. static_assert((int)FILES_STRUCT_NENTRY > 128);
  34. struct files_struct *filesp;
  35. if ((filesp = kmalloc(sizeof(struct files_struct) + FILES_STRUCT_BUFSIZE)) != NULL) {
  36. filesp->pwd = NULL;
  37. filesp->fd_array = (void *)(filesp + 1);
  38. filesp->files_count = 0;
  39. sem_init(&(filesp->files_sem), 1);
  40. fd_array_init(filesp->fd_array);
  41. }
  42. return filesp;
  43. }
  44. //Called when a proc exit
  45. void
  46. files_destroy(struct files_struct *filesp) {
  47. // cprintf("[files_destroy]\n");
  48. assert(filesp != NULL && files_count(filesp) == 0);
  49. if (filesp->pwd != NULL) {
  50. vop_ref_dec(filesp->pwd);
  51. }
  52. int i;
  53. struct file *file = filesp->fd_array;
  54. for (i = 0; i < FILES_STRUCT_NENTRY; i ++, file ++) {
  55. if (file->status == FD_OPENED) {
  56. fd_array_close(file);
  57. }
  58. assert(file->status == FD_NONE);
  59. }
  60. kfree(filesp);
  61. }
  62. void
  63. files_closeall(struct files_struct *filesp) {
  64. // cprintf("[files_closeall]\n");
  65. assert(filesp != NULL && files_count(filesp) > 0);
  66. int i;
  67. struct file *file = filesp->fd_array;
  68. //skip the stdin & stdout
  69. for (i = 2, file += 2; i < FILES_STRUCT_NENTRY; i ++, file ++) {
  70. if (file->status == FD_OPENED) {
  71. fd_array_close(file);
  72. }
  73. }
  74. }
  75. int
  76. dup_files(struct files_struct *to, struct files_struct *from) {
  77. // cprintf("[dup_fs]\n");
  78. assert(to != NULL && from != NULL);
  79. assert(files_count(to) == 0 && files_count(from) > 0);
  80. if ((to->pwd = from->pwd) != NULL) {
  81. vop_ref_inc(to->pwd);
  82. }
  83. int i;
  84. struct file *to_file = to->fd_array, *from_file = from->fd_array;
  85. for (i = 0; i < FILES_STRUCT_NENTRY; i ++, to_file ++, from_file ++) {
  86. if (from_file->status == FD_OPENED) {
  87. /* alloc_fd first */
  88. to_file->status = FD_INIT;
  89. fd_array_dup(to_file, from_file);
  90. }
  91. }
  92. return 0;
  93. }