fix O_RDWR bug.
[mit-jos.git] / lib / console.c
blobda1ab9ba40915337944a50b2796654420dcacf51
2 #include <inc/string.h>
3 #include <inc/lib.h>
5 void
6 cputchar(int ch)
8 char c = ch;
10 // Unlike standard Unix's putchar,
11 // the cputchar function _always_ outputs to the system console.
12 sys_cputs(&c, 1);
15 int
16 getchar(void)
18 unsigned char c;
19 int r;
21 // JOS does, however, support standard _input_ redirection,
22 // allowing the user to redirect script files to the shell and such.
23 // getchar() reads a character from file descriptor 0.
24 r = read(0, &c, 1);
25 if (r < 0)
26 return r;
27 if (r < 1)
28 return -E_EOF;
29 return c;
33 // "Real" console file descriptor implementation.
34 // The putchar/getchar functions above will still come here by default,
35 // but now can be redirected to files, pipes, etc., via the fd layer.
37 static ssize_t cons_read(struct Fd*, void*, size_t, off_t);
38 static ssize_t cons_write(struct Fd*, const void*, size_t, off_t);
39 static int cons_close(struct Fd*);
40 static int cons_stat(struct Fd*, struct Stat*);
42 struct Dev devcons =
44 .dev_id = 'c',
45 .dev_name = "cons",
46 .dev_read = cons_read,
47 .dev_write = cons_write,
48 .dev_close = cons_close,
49 .dev_stat = cons_stat
52 int
53 iscons(int fdnum)
55 int r;
56 struct Fd *fd;
58 if ((r = fd_lookup(fdnum, &fd)) < 0)
59 return r;
60 return fd->fd_dev_id == devcons.dev_id;
63 int
64 opencons(void)
66 int r;
67 struct Fd* fd;
69 if ((r = fd_alloc(&fd)) < 0)
70 return r;
71 if ((r = sys_page_alloc(0, fd, PTE_P|PTE_U|PTE_W|PTE_SHARE)) < 0)
72 return r;
73 fd->fd_dev_id = devcons.dev_id;
74 fd->fd_omode = O_RDWR;
75 return fd2num(fd);
78 ssize_t
79 cons_read(struct Fd *fd, void *vbuf, size_t n, off_t offset)
81 int c;
83 USED(offset);
85 if (n == 0)
86 return 0;
88 while ((c = sys_cgetc()) == 0)
89 sys_yield();
90 if (c < 0)
91 return c;
92 if (c == 0x04) // ctl-d is eof
93 return 0;
94 *(char*)vbuf = c;
95 return 1;
98 ssize_t
99 cons_write(struct Fd *fd, const void *vbuf, size_t n, off_t offset)
101 int tot, m;
102 char buf[128];
104 USED(offset);
106 // mistake: have to nul-terminate arg to sys_cputs,
107 // so we have to copy vbuf into buf in chunks and nul-terminate.
108 for (tot = 0; tot < n; tot += m) {
109 m = n - tot;
110 if (m > sizeof(buf) - 1)
111 m = sizeof(buf) - 1;
112 memmove(buf, (char*)vbuf + tot, m);
113 sys_cputs(buf, m);
115 return tot;
119 cons_close(struct Fd *fd)
121 USED(fd);
123 return 0;
127 cons_stat(struct Fd *fd, struct Stat *stat)
129 strcpy(stat->st_name, "<cons>");
130 return 0;