Skip to content

Instantly share code, notes, and snippets.

@trya
Created May 22, 2018 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trya/dabeae64724dbb333b70e4e944a26717 to your computer and use it in GitHub Desktop.
Save trya/dabeae64724dbb333b70e4e944a26717 to your computer and use it in GitHub Desktop.
Implementation of cat using splice()
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int p[2];
const size_t sz = 65536;
void cat(int fd)
{
ssize_t nb_read, nb_spliced;
while ((nb_read = splice(fd, NULL, p[1], NULL, sz, SPLICE_F_MOVE)) > 0) {
do {
if ((nb_spliced = splice(p[0], NULL, STDOUT_FILENO, NULL, nb_read, SPLICE_F_MOVE)) < 0) {
perror("splice");
exit(EXIT_FAILURE);
}
nb_read -= nb_spliced;
} while (nb_read > 0);
}
if (nb_read < 0) {
perror("splice");
exit(EXIT_FAILURE);
}
}
int main(int argc, char **argv)
{
if (pipe(p) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
if (argc < 2) {
cat(STDIN_FILENO);
exit(EXIT_SUCCESS);
}
int i;
int fd;
for (i = 1; i < argc; i++) {
if ((fd = open(argv[i], O_RDONLY)) < 0) {
perror("open");
exit(EXIT_FAILURE);
}
cat(fd);
close(fd);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment