1/*	$OpenBSD: imsg_subr.c,v 1.1 2015/07/21 04:06:04 yasuoka Exp $	*/
2
3/*
4 * Copyright (c) 2015 YASUOKA Masahiko <yasuoka@yasuoka.net>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18#include <sys/types.h>
19#include <sys/queue.h>
20#include <sys/uio.h>
21
22#include <imsg.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <string.h>
26#include <poll.h>
27#include <errno.h>
28
29#include "imsg_subr.h"
30
31/*
32 * Check readability not to spin before calling imsg_read(3).  Wait 'millisec'
33 * until it becomes readable.
34 */
35int
36imsg_sync_read(struct imsgbuf *ibuf, int millisec)
37{
38	struct pollfd	 fds[1];
39	int		 retval;
40
41	fds[0].fd = ibuf->fd;
42	fds[0].events = POLLIN;
43	retval = poll(fds, 1, millisec);
44	if (retval == 0) {
45		errno = EAGAIN;
46		return (-1);
47	}
48	if (retval > 0 && (fds[0].revents & POLLIN) != 0)
49		return imsg_read(ibuf);
50
51	return (-1);
52}
53
54/*
55 * Check writability not to spin before calling imsg_flush(3).  Wait 'millisec'
56 * until it becomes writable.
57 */
58int
59imsg_sync_flush(struct imsgbuf *ibuf, int millisec)
60{
61	struct pollfd	 fds[1];
62	int		 retval;
63
64	if (!ibuf->w.queued)
65		return (0);	/* already flushed */
66
67	fds[0].fd = ibuf->fd;
68	fds[0].events = POLLOUT;
69	retval = poll(fds, 1, millisec);
70	if (retval == 0) {
71		errno = EAGAIN;
72		return (-1);
73	}
74	if (retval > 0 && (fds[0].revents & POLLOUT) != 0)
75		return imsg_flush(ibuf);
76
77	return (-1);
78}
79