chiark / gitweb /
Switch to GPL v3
[disorder] / lib / logfd.c
... / ...
CommitLineData
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2007 Richard Kettlewell
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#include "common.h"
20
21#include <unistd.h>
22#include <errno.h>
23
24#include "syscalls.h"
25#include "logfd.h"
26#include "event.h"
27#include "log.h"
28
29/* called when bytes are available and at eof */
30static int logfd_readable(ev_source attribute((unused)) *ev,
31 ev_reader *reader,
32 void *ptr,
33 size_t bytes,
34 int eof,
35 void *u) {
36 char *nl;
37 const char *tag = u;
38 int len;
39
40 while((nl = memchr(ptr, '\n', bytes))) {
41 len = nl - (char *)ptr;
42 ev_reader_consume(reader, len + 1);
43 info("%s: %.*s", tag, len, (char *)ptr);
44 ptr = nl + 1;
45 bytes -= len + 1;
46 }
47 if(eof && bytes) {
48 info("%s: %.*s", tag, (int)bytes, (char *)ptr);
49 ev_reader_consume(reader, bytes);
50 }
51 return 0;
52}
53
54/* called when a read error occurs */
55static int logfd_error(ev_source attribute((unused)) *ev,
56 int errno_value,
57 void *u) {
58 const char *tag = u;
59
60 error(errno_value, "error reading log pipe from %s", tag);
61 return 0;
62}
63
64/** @brief Create file descriptor for a subprocess to log to
65 * @param ev Event loop
66 * @param tag Tag for this log
67 * @return File descriptor
68 *
69 * Returns a file descriptor which a subprocess can log to. The normal thing
70 * to do would be to dup2() this fd onto the subprocess's stderr (and to close
71 * it in the parent).
72 *
73 * Any lines written to this fd (i.e. by the subprocess) will be logged via
74 * info(), with @p tag included.
75 */
76int logfd(ev_source *ev, const char *tag) {
77 int p[2];
78
79 xpipe(p);
80 cloexec(p[0]);
81 nonblock(p[0]);
82 if(!ev_reader_new(ev, p[0], logfd_readable, logfd_error, (void *)tag,
83 "logfd"))
84 fatal(errno, "error calling ev_reader_new");
85 return p[1];
86}
87
88/*
89Local Variables:
90c-basic-offset:2
91comment-column:40
92fill-column:79
93indent-tabs-mode:nil
94End:
95*/