-/*
-colcycle - color cycling image viewer
-Copyright (C) 2016 John Tsiombikas <nuclear@member.fsf.org>
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
#include <stdio.h>
-#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <fcntl.h>
#include "logger.h"
-#define LOGFNAME "demo.log"
+static int logfd = -1, orig_fd1 = -1;
-static FILE *logfile;
+int init_logger(const char *fname)
+{
+ if(logfd != -1) return -1;
+
+ if((logfd = open(fname, O_CREAT | O_WRONLY | O_TRUNC, 0644)) == -1) {
+ fprintf(stderr, "init_logger: failed to open %s: %s\n", fname, strerror(errno));
+ return -1;
+ }
+
+ orig_fd1 = dup(1);
+ close(1);
+ close(2);
+ dup(logfd);
+ dup(logfd);
+ return 0;
+}
-void logger_output(FILE *fp)
+void stop_logger(void)
{
- if(logfile) fclose(logfile);
- logfile = fp;
+ if(logfd >= 0) {
+ close(logfd);
+ logfd = -1;
+ }
+ if(orig_fd1 >= 0) {
+ close(1);
+ close(2);
+ dup(orig_fd1);
+ dup(orig_fd1);
+ orig_fd1 = -1;
+ }
}
-void printlog(const char *fmt, ...)
+int print_tail(const char *fname)
{
- va_list ap;
+ FILE *fp;
+ char buf[64];
+ long lineoffs[16];
+ int wr, rd, c;
- if(!logfile) {
- if(!(logfile = fopen(LOGFNAME, "w"))) {
- return;
+ if(!(fp = fopen(fname, "r"))) {
+ return -1;
+ }
+ wr = rd = 0;
+ lineoffs[wr++] = 0;
+ while(fgets(buf, sizeof buf, fp)) {
+ lineoffs[wr] = ftell(fp);
+ wr = (wr + 1) & 0xf;
+ if(wr == rd) {
+ rd = (rd + 1) & 0xf;
}
- setvbuf(logfile, 0, _IOLBF, 0);
}
- va_start(ap, fmt);
- vfprintf(logfile, fmt, ap);
- va_end(ap);
+ fseek(fp, lineoffs[rd], SEEK_SET);
+ while((c = fgetc(fp)) != -1) {
+ fputc(c, stdout);
+ }
+ fclose(fp);
+ return 0;
}