2 * collectd - src/utils_tail.c
3 * Copyright (C) 2007-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
28 #include "utils_tail.h"
37 cu_tail_t *cu_tail_create (const char *file)
41 obj = (cu_tail_t *) malloc (sizeof (cu_tail_t));
44 memset (obj, '\0', sizeof (cu_tail_t));
46 obj->file = strdup (file);
47 if (obj->file == NULL)
56 } /* cu_tail_t *cu_tail_create */
58 int cu_tail_destroy (cu_tail_t *obj)
66 } /* int cu_tail_destroy */
68 int cu_tail_readline (cu_tail_t *obj, char *buf, int buflen)
76 if (stat (obj->file, &stat_now) != 0)
79 ERROR ("cu_tail_readline: stat (%s) failed: %s",
81 sstrerror (errno, errbuf, sizeof (errbuf)));
85 if ((stat_now.st_dev != obj->stat.st_dev) ||
86 (stat_now.st_ino != obj->stat.st_ino))
89 * If the file was replaced open the new file and close the
94 new_fd = fopen (obj->file, "r");
98 ERROR ("cu_tail_readline: open (%s) failed: %s",
100 sstrerror (errno, errbuf,
105 /* If there was no previous file, seek to the end. We don't
106 * want to read in the entire file, usually. */
107 if (obj->stat.st_ino == 0)
108 fseek (new_fd, 0, SEEK_END);
115 else if (stat_now.st_size < obj->stat.st_size)
118 * Else, if the file was not replaces, but the file was
119 * truncated, seek to the beginning of the file.
121 assert (obj->fd != NULL);
126 if (fgets (buf, buflen, obj->fd) == NULL)
128 if (feof (obj->fd) == 0)
130 else /* an error occurred */
135 memcpy (&obj->stat, &stat_now, sizeof (struct stat));
138 } /* int cu_tail_readline */
140 int cu_tail_read (cu_tail_t *obj, char *buf, int buflen, tailfunc *callback,
145 while ((status = cu_tail_readline (obj, buf, buflen)) == 0)
151 status = callback (data, buf, buflen);
157 } /* int cu_tail_read */