1 /* Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file stdin.c Functions that deal with reading from stdin. */
13 #include "buffer_tree.h"
17 * If there is space left in the buffer of the stdin task, ask the scheduler to
18 * monitor STDIN_FILENO.
20 static void stdin_pre_monitor(struct sched *s, void *context)
22 struct stdin_task *sit = context;
25 ret = btr_node_status(sit->btrn, 0, BTR_NT_ROOT);
30 if (btr_pool_unused(sit->btrp) > 0)
31 return sched_monitor_readfd(STDIN_FILENO, s);
32 sched_request_timeout_ms(100, s);
36 * Feed data from stdin into the buffer tree if STDIN_FILENO is ready for
39 static int stdin_post_monitor(__a_unused struct sched *s, void *context)
41 struct stdin_task *sit = context;
46 ret = btr_node_status(sit->btrn, 0, BTR_NT_ROOT);
51 sz = btr_pool_get_buffer(sit->btrp, &buf);
54 if (sit->must_set_nonblock_flag) {
55 ret = mark_fd_nonblocking(STDIN_FILENO);
58 sit->must_set_nonblock_flag = false;
61 * Do not use the maximal size to avoid having only a single buffer
62 * reference for the whole pool. This is bad because if that single
63 * reference can not be freed, we're stuck.
65 sz = PARA_MIN(sz, btr_pool_size(sit->btrp) / 2);
66 ret = read_nonblock(STDIN_FILENO, buf, sz, &n);
68 btr_add_output_pool(sit->btrp, n, sit->btrn);
72 btr_remove_node(&sit->btrn);
73 /* Revert to blocking mode if necessary. */
74 fcntl(STDIN_FILENO, F_SETFL, sit->fd_flags);
75 //btr_pool_free(sit->btrp);
80 * Register a stdin task structure.
82 * \param sit The stdin task structure to register.
83 * \param s The task will be added to this scheduler's task list.
85 * This allocates a buffer tree pool for I/O, sets up \a sit and registers a
86 * task with \a sit as context pointer.
88 void stdin_task_register(struct stdin_task *sit, struct sched *s)
91 struct task_info ti = {
93 .pre_monitor = stdin_pre_monitor,
94 .post_monitor = stdin_post_monitor,
98 sit->btrp = btr_pool_new("stdin", 128 * 1024);
100 * Both STDIN_FILENO and STDOUT_FILENO may refer to the same open file
101 * description (the terminal), and thus share the same file status
102 * flags. In order to not interfere with the stdout task, we only get
103 * the file status flags for STDIN here and save a copy. The nonblock
104 * flag is set later on the first read.
106 ret = fcntl(STDIN_FILENO, F_GETFL);
108 PARA_EMERG_LOG("F_GETFL: %s\n", strerror(errno));
112 sit->must_set_nonblock_flag = (sit->fd_flags & O_NONBLOCK) == 0
113 && !isatty(STDIN_FILENO);
114 sit->task = task_register(&ti, s);