Browse Source

libc: set errno on read, write

K. Lange 2 years ago
parent
commit
e2b6f13ba2
3 changed files with 17 additions and 2 deletions
  1. 13 0
      apps/cat.c
  2. 2 1
      libc/unistd/read.c
  3. 2 1
      libc/unistd/write.c

+ 13 - 0
apps/cat.c

@@ -19,27 +19,40 @@
 
 #define CHUNK_SIZE 4096
 
+static char * _argv_0;
+static char * _file;
+
 void doit(int fd) {
 	while (1) {
 		char buf[CHUNK_SIZE];
 		memset(buf, 0, CHUNK_SIZE);
 		ssize_t r = read(fd, buf, CHUNK_SIZE);
 		if (!r) return;
+		if (r < 0) {
+			fprintf(stderr, "%s: %s: %s\n", _argv_0, _file, strerror(errno));
+			return;
+		}
 		write(STDOUT_FILENO, buf, r);
 	}
 }
 
 int main(int argc, char ** argv) {
 	int ret = 0;
+
+	_argv_0 = argv[0];
+
 	if (argc == 1) {
+		_file = "stdin";
 		doit(0);
 	}
 
 	for (int i = 1; i < argc; ++i) {
 		if (!strcmp(argv[i],"-")) {
+			_file = "stdin";
 			doit(0);
 			continue;
 		}
+		_file = argv[i];
 		int fd = open(argv[i], O_RDONLY);
 		if (fd < 0) {
 			fprintf(stderr, "%s: %s: %s\n", argv[0], argv[i], strerror(errno));

+ 2 - 1
libc/unistd/read.c

@@ -1,9 +1,10 @@
 #include <unistd.h>
+#include <errno.h>
 #include <syscall.h>
 #include <syscall_nums.h>
 
 DEFN_SYSCALL3(read,  SYS_READ, int, char *, int);
 
 int read(int file, void *ptr, size_t len) {
-	return syscall_read(file,ptr,len);
+	__sets_errno(syscall_read(file,ptr,len));
 }

+ 2 - 1
libc/unistd/write.c

@@ -1,9 +1,10 @@
 #include <unistd.h>
+#include <errno.h>
 #include <syscall.h>
 #include <syscall_nums.h>
 
 DEFN_SYSCALL3(write, SYS_WRITE, int, char *, int);
 
 ssize_t write(int file, const void *ptr, size_t len) {
-	return syscall_write(file,(char *)ptr,len);
+	__sets_errno(syscall_write(file,(char *)ptr,len));
 }