Skip to content

Instantly share code, notes, and snippets.

@troglobit
Last active October 17, 2018 16:14
Show Gist options
  • Save troglobit/f969076a2bc2aff6ee6de2b8bf6e41c3 to your computer and use it in GitHub Desktop.
Save troglobit/f969076a2bc2aff6ee6de2b8bf6e41c3 to your computer and use it in GitHub Desktop.
tail in C, available under the ISC license
/*
* Copyright (c) 2018 Joachim Nilsson <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <err.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int fd;
if (argc < 2)
return 1;
fd = open(argv[1], O_RDONLY | O_NONBLOCK);
if (fd < 0)
err(1, "Failed opening %s", argv[1]);
while (1) {
struct pollfd pfd = {
.fd = fd,
.events = POLLIN
};
ssize_t num;
char buf[80];
int rc;
rc = poll(&pfd, 1, 1000);
if (rc < 0) {
warn("poll");
sleep(1);
continue;
}
if (rc == 0) {
warn("timeout");
continue;
}
num = read(fd, buf, sizeof(buf));
if (!num) {
sleep(1);
continue;
}
if (num < 0) {
warn("read failed");
continue;
}
num = write(STDOUT_FILENO, buf, num);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment