Merge branch 'maint'
[paraslash.git] / stdout.c
1 /*
2 * Copyright (C) 2006-2014 Andre Noll <maan@tuebingen.mpg.de>
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 /* Add STDOUT_FILENO to the write fd set if there is input data available. */
20 static void stdout_pre_select(struct sched *s, void *context)
21 {
22 struct stdout_task *sot = context;
23 int ret;
24
25 ret = btr_node_status(sot->btrn, 0, BTR_NT_LEAF);
26 if (ret > 0)
27 para_fd_set(STDOUT_FILENO, &s->wfds, &s->max_fileno);
28 else if (ret < 0)
29 sched_min_delay(s);
30 }
31
32 /*
33 * This function writes input data from the buffer tree to stdout if
34 * STDOUT_FILENO is writable.
35 */
36 static int stdout_post_select(struct sched *s, void *context)
37 {
38 struct stdout_task *sot = context;
39 struct btr_node *btrn = sot->btrn;
40 int ret;
41 char *buf;
42 size_t sz;
43
44 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
45 if (ret < 0)
46 goto out;
47 if (ret == 0)
48 return 0;
49 if (!FD_ISSET(STDOUT_FILENO, &s->wfds))
50 return 0;
51
52 if (sot->must_set_nonblock_flag) {
53 ret = mark_fd_nonblocking(STDOUT_FILENO);
54 if (ret < 0)
55 goto out;
56 sot->must_set_nonblock_flag = false;
57 }
58 for (;;) {
59 sz = btr_next_buffer(btrn, &buf);
60 if (sz == 0)
61 break;
62 ret = xwrite(STDOUT_FILENO, buf, sz);
63 if (ret <= 0)
64 break;
65 btr_consume(btrn, ret);
66 }
67 out:
68 if (ret < 0) {
69 btr_remove_node(&sot->btrn);
70 /* Revert to blocking mode if necessary. */
71 fcntl(STDOUT_FILENO, F_SETFL, sot->fd_flags);
72 }
73 return ret;
74 }
75
76 /**
77 * Register a stdout task structure.
78 *
79 * \param sot The stdout task structure to register.
80 * \param s The task will be added to this scheduler's task list.
81 *
82 * This sets up \a sot and registers a task with \a sot as context pointer.
83 */
84 void stdout_task_register(struct stdout_task *sot, struct sched *s)
85 {
86 int ret;
87 struct task_info ti = {
88 .pre_select = stdout_pre_select,
89 .post_select = stdout_post_select,
90 .context = sot,
91 .name = "stdout",
92 };
93
94 /* See stdin.c for details. */
95 ret = fcntl(STDOUT_FILENO, F_GETFL);
96 if (ret < 0) {
97 PARA_EMERG_LOG("F_GETFL: %s\n", strerror(errno));
98 exit(EXIT_FAILURE);
99 }
100 sot->fd_flags = ret;
101 sot->must_set_nonblock_flag = (sot->fd_flags & O_NONBLOCK) == 0;
102 sot->task = task_register(&ti, s);
103 }