Merge branch 't/libao'
[paraslash.git] / stdout.c
1 /*
2 * Copyright (C) 2006-2011 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file stdout.c Functions that deal with writing to stdout. */
8
9 #include <assert.h>
10 #include <stdbool.h>
11
12 #include "para.h"
13 #include "list.h"
14 #include "sched.h"
15 #include "fd.h"
16 #include "error.h"
17 #include "stdout.h"
18 #include "buffer_tree.h"
19
20 /**
21 * The pre_select function of the stdout task.
22 *
23 * \param s The scheduler this task was registered to.
24 * \param t The task structure of the stdout task.
25 *
26 * This function is always successful. If there is input data available, it
27 * adds \p STDOUT_FILENO to the write fd set of \a s.
28 */
29 static void stdout_pre_select(struct sched *s, struct task *t)
30 {
31 struct stdout_task *sot = container_of(t, struct stdout_task, task);
32 int ret;
33
34 t->error = 0;
35 ret = btr_node_status(sot->btrn, 0, BTR_NT_LEAF);
36 if (ret > 0)
37 para_fd_set(STDOUT_FILENO, &s->wfds, &s->max_fileno);
38 else if (ret < 0)
39 sched_min_delay(s);
40 }
41
42 /**
43 * The post select function of the stdout task.
44 *
45 * \param s The scheduler this task was registered to.
46 * \param t The task structure of the stdout task.
47 *
48 * This function writes input data from the buffer tree to stdout if \p
49 * STDOUT_FILENO is writable.
50 */
51 static void stdout_post_select(struct sched *s, struct task *t)
52 {
53 struct stdout_task *sot = container_of(t, struct stdout_task, task);
54 struct btr_node *btrn = sot->btrn;
55 int ret;
56 char *buf;
57 size_t sz;
58
59 t->error = 0;
60 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
61 if (ret < 0)
62 goto out;
63 if (ret == 0)
64 return;
65 if (!FD_ISSET(STDOUT_FILENO, &s->wfds))
66 return;
67
68 for (;;) {
69 sz = btr_next_buffer(btrn, &buf);
70 if (sz == 0)
71 break;
72 ret = write_nonblock(STDOUT_FILENO, buf, sz);
73 if (ret <= 0)
74 break;
75 btr_consume(btrn, ret);
76 }
77 out:
78 if (ret < 0)
79 btr_remove_node(btrn);
80 t->error = ret;
81 }
82 /**
83 * Initialize a stdout task structure with default values.
84 *
85 * \param sot The stdout task structure.
86 *
87 * This fills in the pre/post select function pointers of the task structure
88 * given by \a sot and sets the stdout file descriptor to nonblocking mode.
89 */
90 void stdout_set_defaults(struct stdout_task *sot)
91 {
92 int ret;
93
94 sot->task.pre_select = stdout_pre_select;
95 sot->task.post_select = stdout_post_select;
96 sprintf(sot->task.status, "stdout");
97 ret = mark_fd_nonblocking(STDOUT_FILENO);
98 if (ret >= 0)
99 return;
100 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
101 exit(EXIT_FAILURE);
102 }