commit: 5e09cd798fa4bb05eeb642a1788b0c678e3c0363
parent 4b36bf0836473a45d345a98cbeac38291b192a35
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Thu, 28 Mar 2024 18:43:58 +0100
cmd/cat: assert(errno == 0)
Diffstat:
1 file changed, 14 insertions(+), 1 deletion(-)
diff --git a/cmd/cat.c b/cmd/cat.c
@@ -4,7 +4,8 @@
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE /* splice(2) */
-#include <errno.h> /* errno */
+#include <assert.h>
+#include <errno.h>
#include <fcntl.h> /* open(), O_RDONLY, splice(2) */
#include <stdint.h> /* SIZE_MAX */
#include <stdio.h> /* fprintf(), BUFSIZ */
@@ -17,11 +18,14 @@ concat(int fd, const char *fdname)
ssize_t c;
char buf[BUFSIZ];
+ assert(errno == 0);
while((c = read(fd, buf, sizeof(buf))) > 0)
{
+ assert(errno == 0);
if(write(1, buf, (size_t)c) < 0)
{
fprintf(stderr, "cat: Error writing: %s\n", strerror(errno));
+ errno = 0;
return 1;
}
}
@@ -29,6 +33,7 @@ concat(int fd, const char *fdname)
if(c < 0)
{
fprintf(stderr, "cat: Error reading ‘%s’: %s\n", fdname, strerror(errno));
+ errno = 0;
return 1;
}
@@ -42,6 +47,7 @@ fd_copy(int fd, const char *fdname)
ssize_t c = 0;
again:
+ assert(errno == 0);
while((c = splice(
fd, NULL, 1, NULL, SIZE_MAX, SPLICE_F_MOVE | SPLICE_F_NONBLOCK | SPLICE_F_MORE)) > 0)
;
@@ -50,13 +56,16 @@ again:
{
if(errno == EINVAL)
{
+ errno = 0;
return concat(fd, fdname);
}
if(errno == EAGAIN)
{
+ errno = 0;
goto again;
}
fprintf(stderr, "cat: Error copying ‘%s’: %s\n", fdname, strerror(errno));
+ errno = 0;
return 1;
}
@@ -96,10 +105,12 @@ main(int argc, char *argv[])
}
else
{
+ assert(errno == 0);
int fd = open(argv[argi], O_RDONLY);
if(fd < 0)
{
fprintf(stderr, "cat: Error opening ‘%s’: %s\n", argv[argi], strerror(errno));
+ errno = 0;
return 1;
}
@@ -108,9 +119,11 @@ main(int argc, char *argv[])
return 1;
}
+ assert(errno == 0);
if(close(fd) < 0)
{
fprintf(stderr, "cat: Error closing ‘%s’: %s\n", argv[argi], strerror(errno));
+ errno = 0;
return 1;
}
}