New developer version 0.6.8; added select () function; added demonstrating example...
[ZeXOS.git] / kernel / core / fd.c
blob498190937521ae62067ff1d059cd8a7ba23f7611
1 /*
2 * ZeX/OS
3 * Copyright (C) 2008 Tomas 'ZeXx86' Jedrzejek (zexx86@zexos.org)
4 * Copyright (C) 2009 Martin 'povik' Poviser (martin.povik@gmail.com)
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include <build.h>
22 #include <system.h>
23 #include <string.h>
24 #include <fd.h>
25 #include <errno.h>
27 fd_t fd_list;
29 fd_t *fd_get (int id)
31 fd_t *fd;
32 for (fd = fd_list.next; fd != &fd_list; fd = fd->next) {
33 if (fd->id == (unsigned) id)
34 return fd;
37 return 0;
40 fd_t *fd_create (int flags)
42 int id = 0;
43 fd_t *fd = kmalloc (sizeof (fd_t));
45 if (!fd) {
46 errno_set (ENOMEM);
47 return 0;
50 while (id >= 0) {
51 id ++;
52 if (!fd_get (id))
53 break;
56 if (id < 0) {
57 errno_set (ENFILE);
58 return 0;
61 fd->id = id;
62 fd->flags = flags;
64 fd->e = 1;
65 fd->s = (char *) 0;
66 fd->p = 0;
67 fd->path = 0;
68 fd->proc = 0;
70 /* add into list */
71 fd->next = &fd_list;
72 fd->prev = fd_list.prev;
73 fd->prev->next = fd;
74 fd->next->prev = fd;
76 return fd;
79 int fd_delete (fd_t *fd)
81 if (!fd)
82 return 0;
84 if (fd->path)
85 kfree (fd->path);
87 fd->s = 0;
88 fd->e = 0;
89 fd->flags = 0;
90 fd->id = 0;
91 fd->p = 0;
92 fd->dev = 0;
93 fd->proc = 0;
95 /* delete old file descriptor from fd_list */
96 fd->next->prev = fd->prev;
97 fd->prev->next = fd->next;
99 kfree (fd);
101 return 1;
104 unsigned int init_fd ()
106 fd_list.next = &fd_list;
107 fd_list.prev = &fd_list;
109 /* HACK: first we need create file descriptor 0 and 1 for stdout and stdin */
110 stdin = fd_create (0);
111 stdout = fd_create (0);
113 return 1;