]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - text-utils/tailf.c
1 /* tailf.c -- tail a log file and then follow it
2 * Created: Tue Jan 9 15:49:21 1996 by faith@acm.org
3 * Copyright 1996, 2003 Rickard E. Faith (faith@acm.org)
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included
13 * in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21 * OTHER DEALINGS IN THE SOFTWARE.
23 * less -F and tail -f cause a disk access every five seconds. This
24 * program avoids this problem by waiting for the file size to change.
25 * Hence, the file is not accessed, and the access time does not need to be
26 * flushed back to disk. This is sort of a "stealth" tail.
36 static size_t filesize(const char *filename
)
40 if (!stat(filename
, &sb
)) return sb
.st_size
;
44 static void tailf(const char *filename
, int lines
)
52 if (!(str
= fopen(filename
, "r"))) {
53 fprintf(stderr
, _("Cannot open \"%s\" for read\n"), filename
);
58 buffer
= malloc(lines
* sizeof(*buffer
));
59 for (i
= 0; i
< lines
; i
++) buffer
[i
] = malloc(BUFSIZ
+ 1);
61 while (fgets(buffer
[tail
], BUFSIZ
, str
)) {
62 if (++tail
>= lines
) {
69 for (i
= tail
; i
< lines
; i
++) fputs(buffer
[i
], stdout
);
70 for (i
= 0; i
< tail
; i
++) fputs(buffer
[i
], stdout
);
72 for (i
= head
; i
< tail
; i
++) fputs(buffer
[i
], stdout
);
76 for (i
= 0; i
< lines
; i
++) free(buffer
[i
]);
80 int main(int argc
, char **argv
)
88 setlocale(LC_ALL
, "");
89 bindtextdomain(PACKAGE
, LOCALEDIR
);
93 fprintf(stderr
, _("Usage: tailf logfile\n"));
101 for (osize
= filesize(filename
);;) {
102 nsize
= filesize(filename
);
103 if (nsize
!= osize
) {
104 if (!(str
= fopen(filename
, "r"))) {
105 fprintf(stderr
, _("Cannot open \"%s\" for read\n"), filename
);
109 if (!fseek(str
, osize
, SEEK_SET
))
110 while ((count
= fread(buffer
, 1, sizeof(buffer
), str
)) > 0)
111 fwrite(buffer
, 1, count
, stdout
);
116 usleep(250000); /* 250mS */