- 论坛徽章:
- 2
|
我所理解的近似于文件系统内核的代码
- struct file { /* shared within processes */
- int counter;
- ... ....
- };
- struct pcb { /* process private */
- struct file *fd[16];
- };
- int get_free_fd(struct pcb *p)
- {
- int i;
- for (i = 0; i < 16; i++) {
- if (p->fd[i] == NULL) {
- return i;
- }
- }
- return -1;
- }
- int dup(struct pcb *p, int i)
- {
- int new_fd;
- new_fd = get_free_fd(p);
- if (new_fd >= 0) {
- ++p->fd[i]->counter;
- p->fd[new_fd] == p->fd[i];
- return new_fd;
- }
- return -1;
- }
- int close(struct pcb *p, int i)
- {
- struct file *fp;
- fp = p->fd[i];
- if (fp != NULL && fp->counter > 0) {
- if (--fp->counter == 0) {
- close_file(fp);
- free_file(fp);
- }
- p->fd[i] = NULL;
- return 0;
- }
- return -1;
- }
- int close_all(struct pcb *p)
- {
- int i;
- for (i = 0; i < 16; i++) {
- if (p->fd[i] != NULL) {
- close(p, i);
- p->fd[i] = NULL;
- }
- }
- return 0;
- }
复制代码 |
|