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)
75 ERROR ("utils_tail: cu_tail_readline: buflen too small: "
80 if (stat (obj->file, &stat_now) != 0)
83 ERROR ("cu_tail_readline: stat (%s) failed: %s",
85 sstrerror (errno, errbuf, sizeof (errbuf)));
89 if ((stat_now.st_dev != obj->stat.st_dev) ||
90 (stat_now.st_ino != obj->stat.st_ino))
93 * If the file was replaced open the new file and close the
98 DEBUG ("utils_tail: cu_tail_readline: (Re)Opening %s..",
101 new_fd = fopen (obj->file, "r");
105 ERROR ("utils_tail: cu_tail_readline: open (%s) failed: %s",
107 sstrerror (errno, errbuf,
112 /* If there was no previous file, seek to the end. We don't
113 * want to read in the entire file, usually. */
114 if (obj->stat.st_ino == 0)
115 fseek (new_fd, 0, SEEK_END);
122 else if (stat_now.st_size < obj->stat.st_size)
125 * Else, if the file was not replaces, but the file was
126 * truncated, seek to the beginning of the file.
128 assert (obj->fd != NULL);
133 if (fgets (buf, buflen, obj->fd) == NULL)
135 if (feof (obj->fd) != 0)
137 else /* an error occurred */
139 ERROR ("utils_tail: cu_tail_readline: fgets returned "
146 memcpy (&obj->stat, &stat_now, sizeof (struct stat));
149 } /* int cu_tail_readline */
151 int cu_tail_read (cu_tail_t *obj, char *buf, int buflen, tailfunc_t *callback,
158 status = cu_tail_readline (obj, buf, buflen);
161 ERROR ("utils_tail: cu_tail_read: cu_tail_readline "
170 status = callback (data, buf, buflen);
173 ERROR ("utils_tail: cu_tail_read: callback returned "
174 "status %i.", status);
180 } /* int cu_tail_read */