Buffer char writes for printf, fprintf, and die.

This results in fewer garbaled userspace console outputs.
上级 b27ae5e9
...@@ -3,33 +3,67 @@ ...@@ -3,33 +3,67 @@
#include "user.h" #include "user.h"
#include <stdarg.h> #include <stdarg.h>
#include "fmt.hh" #include "fmt.hh"
#include "lib.h"
struct outbuf {
char b[128];
int n;
int fd;
};
static void
flushoutbuf(struct outbuf* b)
{
int i = 0;
int r;
while (b->n != 0) {
r = write(b->fd, &b->b[i], b->n);
if (r == 0 || r < 0) {
b->n = 0;
} else {
b->n -= r;
i += r;
}
}
}
// Print to the given fd.
static void static void
writec(int c, void *arg) writeoutbuf(int c, void *arg)
{ {
int fd = (int) (u64) arg; struct outbuf* b = (struct outbuf*)arg;
write(fd, &c, 1); if (b->n == NELEM(b->b))
flushoutbuf(b);
b->b[b->n] = c;
b->n++;
} }
void void
fprintf(int fd, const char *fmt, ...) fprintf(int fd, const char *fmt, ...)
{ {
struct outbuf b;
va_list ap; va_list ap;
b.n = 0;
b.fd = fd;
va_start(ap, fmt); va_start(ap, fmt);
vprintfmt(writec, (void*) (u64)fd, fmt, ap); vprintfmt(writeoutbuf, (void*) &b, fmt, ap);
va_end(ap); va_end(ap);
flushoutbuf(&b);
} }
void void
printf(const char *fmt, ...) printf(const char *fmt, ...)
{ {
struct outbuf b;
va_list ap; va_list ap;
b.n = 0;
b.fd = 1;
va_start(ap, fmt); va_start(ap, fmt);
vprintfmt(writec, (void*) 1, fmt, ap); vprintfmt(writeoutbuf, (void*) &b, fmt, ap);
va_end(ap); va_end(ap);
flushoutbuf(&b);
} }
// Print to a buffer. // Print to a buffer.
...@@ -69,11 +103,15 @@ snprintf(char *buf, u32 n, const char *fmt, ...) ...@@ -69,11 +103,15 @@ snprintf(char *buf, u32 n, const char *fmt, ...)
void __attribute__((noreturn)) void __attribute__((noreturn))
die(const char* errstr, ...) die(const char* errstr, ...)
{ {
struct outbuf b;
va_list ap; va_list ap;
b.n = 0;
b.fd = 2;
va_start(ap, errstr); va_start(ap, errstr);
vprintfmt(writec, (void*) (u64)1, errstr, ap); vprintfmt(writeoutbuf, (void*)&b, errstr, ap);
va_end(ap); va_end(ap);
flushoutbuf(&b);
fprintf(2, "\n"); fprintf(2, "\n");
exit(); exit();
} }
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论