Skip to content

Commit

Permalink
✨ 🐛 close file descriptors
Browse files Browse the repository at this point in the history
  • Loading branch information
ianchen-tw committed May 31, 2021
1 parent e1bffb9 commit fcbf237
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 13 deletions.
2 changes: 1 addition & 1 deletion impl-c/fs/vfs.c
Expand Up @@ -173,7 +173,7 @@ struct file *vfs_open(const char *pathname, int flags) {
}

int vfs_close(struct file *file) {
// 1. release the file descriptor
kfree(file);
return 0;
}

Expand Down
3 changes: 3 additions & 0 deletions impl-c/include/proc/task.h
Expand Up @@ -41,6 +41,9 @@ struct task_struct {
};

struct task_struct *task_create(void *func);

void task_free(struct task_struct *task);

void cur_task_exit();

extern uint32_t new_tid;
Expand Down
11 changes: 1 addition & 10 deletions impl-c/proc/sched.c
Expand Up @@ -69,17 +69,8 @@ void kill_zombies() {
task = ((struct task_entry *)entry)->task;
log_println("recycle space for task:%d", task->id);
list_del(entry);

kfree(entry);
// TODO: manage parent code free and child code free
// if (task->code) {
// kfree(task->code);
// }
if (task->user_stack) {
kfree((void *)task->user_stack);
}
kfree((void *)task->kernel_stack);
kfree(task);
task_free(task);
}
}

Expand Down
39 changes: 37 additions & 2 deletions impl-c/proc/task.c
Expand Up @@ -28,6 +28,7 @@ static const int _DO_LOG = 0;
static void foo();

extern void fork_child_eret();
static inline void close_fd(struct task_struct *task, int fd);

uint32_t new_tid = 0;

Expand Down Expand Up @@ -70,6 +71,25 @@ struct task_struct *task_create(void *func) {
return t;
}

void task_free(struct task_struct *task) {
// TODO: manage parent code free and child code free
// if (task->code) {
// kfree(task->code);
// }
if (task->user_stack) {
kfree((void *)task->user_stack);
}
kfree((void *)task->kernel_stack);

// Close all file descriptors
for (int i = 0; i < TASK_MX_NUM_FD; i++) {
if (task->fd[i] != NULL) {
close_fd(task, i);
}
}
kfree(task);
}

int sys_getpid() {
struct task_struct *task = get_current();
return task->id;
Expand All @@ -94,20 +114,35 @@ int sys_open(const char *pathname, int flags) {
for (int i = 0; i < TASK_MX_NUM_FD; i++) {
if (task->fd[i] == NULL) {
task->fd[i] = file;
task->fd_size++;
return i;
}
}
// Should not this line
return -1;
}

void close_fd(struct task_struct *task, int fd) {
if (task->fd[fd] != NULL) {
vfs_close(task->fd[fd]);
task->fd[fd] = NULL;
}
// check for bugs
task->fd_size--;
if (task->fd_size < 0) {
uart_println("[Task free] BUG!!! fd not synce");
while (1) {
;
}
}
}

int sys_close(int fd) {
struct task_struct *task = get_current();
if ((fd < 0 || fd > TASK_MX_NUM_FD) || (task->fd[fd] == NULL)) {
return -1;
}
task->fd[fd] = NULL;
task->fd_size--;
close_fd(task, fd);
return 0;
}

Expand Down

0 comments on commit fcbf237

Please sign in to comment.