2 * collectd - src/utils_tail.c
3 * Copyright (C) 2008 C-Ware, Inc.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Luke Heberling <lukeh at c-ware.com>
22 * Encapsulates useful code for plugins which must watch for appends to
27 #include "utils_tail.h"
40 cu_tail_t *cu_tail_create (const char *file)
44 obj = (cu_tail_t *) malloc (sizeof (cu_tail_t));
47 memset (obj, '\0', sizeof (cu_tail_t));
49 obj->file = strdup (file);
50 if (obj->file == NULL)
59 } /* cu_tail_t *cu_tail_create */
61 int cu_tail_destroy (cu_tail_t *obj)
69 } /* int cu_tail_destroy */
71 int cu_tail_readline (cu_tail_t *obj, char *buf, int buflen)
82 if (stat (obj->file, &stat_now) != 0)
85 if (stat_now.st_dev != obj->stat.st_dev ||
86 stat_now.st_ino != obj->stat.st_ino)
88 new_fd = fopen (obj->file, "r");
92 if (obj->stat.st_ino == 0)
93 fseek (new_fd, 0, SEEK_END);
99 else if (stat_now.st_size < obj->stat.st_size)
104 memcpy (&obj->stat, &stat_now, sizeof (struct stat));
106 if (fgets (buf, buflen, obj->fd) == NULL && feof (obj->fd) == 0)
110 if (len > 0 && *(buf + len - 1) != '\n' && feof (obj->fd))
112 fseek (obj->fd, -len, SEEK_CUR);
117 } /* int cu_tail_readline */
119 int cu_tail_read (cu_tail_t *obj, char *buf, int buflen, tailfunc *func, void *data)
123 while ((ret = cu_tail_readline (obj, buf, buflen)) == 0)
124 if (*buf == '\0' || (ret = func (data, buf, buflen)))
128 } /* int cu_tail_read */