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