diff --git a/src/userprog/process.c b/src/userprog/process.c index fb421c5..73d77af 100644 --- a/src/userprog/process.c +++ b/src/userprog/process.c @@ -338,6 +338,10 @@ process_exit (void) printf ("%s: exit(%d)\n", cur->name, cur->exit_status); + /* Clean up all open files */ + hash_destroy (&cur->open_files, fd_cleanup); + + /* Close the executable file. */ if (cur->exec_file != NULL) { lock_acquire (&filesys_lock); diff --git a/src/userprog/syscall.c b/src/userprog/syscall.c index b1ce4cc..35bc3db 100644 --- a/src/userprog/syscall.c +++ b/src/userprog/syscall.c @@ -378,6 +378,20 @@ fd_less (const struct hash_elem *a_, const struct hash_elem *b_, return a->fd < b->fd; } +/* Function to clean up an open file entry. Closes the file and frees the + associated memory. */ +void +fd_cleanup (struct hash_elem *e, void *aux UNUSED) +{ + struct open_file *file_info = hash_entry (e, struct open_file, elem); + + lock_acquire (&filesys_lock); + file_close (file_info->file); + lock_release (&filesys_lock); + + free (file_info); +} + /* Gets a file from its descriptor (FD number). If there is no file with the fd FD it returns NULL. */ static struct open_file * diff --git a/src/userprog/syscall.h b/src/userprog/syscall.h index 16af00c..681a8fb 100644 --- a/src/userprog/syscall.h +++ b/src/userprog/syscall.h @@ -14,5 +14,6 @@ void syscall_init (void); unsigned fd_hash (const struct hash_elem *element, void *aux); bool fd_less (const struct hash_elem *a, const struct hash_elem *b, void *aux); +void fd_cleanup (struct hash_elem *e, void *aux); #endif /* userprog/syscall.h */