Skip to content

Commit

Permalink
Fixed bug where sendfile will fail with EINVAL
Browse files Browse the repository at this point in the history
Not all Unix's come with the same implementation of sendfile.
This change attempts it, but if it fails it does normal sys read and
write. Sendfile is way faster than sys read and write, so it is worth
attempting
  • Loading branch information
mckenney5 committed Jun 7, 2023
1 parent 96ef4c7 commit d57ff64
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/cat.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ void throw_error(const char* extra_msg, const int exit_code){
}
void cat(const int fd, const char no_buf, size_t size){
/* reads from the file descriptor into buf, until zero bytes are read */
if(fd == STDIN_FILENO || size > MAX_SENDFILE_LINUX){
//tries sendfile if available (since it is faster, if not, do sys read & write)
if(fd == STDIN_FILENO || size > MAX_SENDFILE_LINUX || sendfile(STDOUT_FILENO, fd, 0, size) != size){
size_t r = 0;
if(no_buf) size = 1;
void *buf = (void*)malloc(size);
Expand All @@ -31,8 +32,8 @@ void cat(const int fd, const char no_buf, size_t size){
if(write(STDOUT_FILENO, buf, r) != r) throw_error(NULL, 3); //if writing stops for some reason
if(r == -1) throw_error(NULL, 1); //if read(2) throws an error
free(buf);
} else //if we are given a file, use the sendfile syscall for better speed
if(sendfile(STDOUT_FILENO, fd, 0, size) != size) throw_error("In sendfile", 1);
} //else
// throw_error("Unable to cat file.", 1);
}
void get_file(const char* file_name, const char no_buf){
/* tries to open the user's file, then calls cat() with its file pointer */
Expand Down

0 comments on commit d57ff64

Please sign in to comment.