audio_format_name(): Add an assert().
[paraslash.git] / stdin.c
1 /*
2 * Copyright (C) 2006 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file stdin.c functions that deal with reading from stdin */
8
9 #include "para.h"
10 #include "string.h"
11 #include "list.h"
12 #include "sched.h"
13 #include "fd.h"
14 #include "error.h"
15 #include "stdin.h"
16
17 /**
18 * the pre_select function of the stdin task
19 *
20 * \param s the scheduler this task was registered to
21 * \param t the task structure of the stdin task
22 *
23 * This function is always successful. If there is space left in the
24 * buffer of the stdin task, it adds \p STDIN_FILENO to the read fd set
25 * of \a s.
26 */
27 void stdin_pre_select(struct sched *s, struct task *t)
28 {
29 struct stdin_task *sit = t->private_data;
30 t->ret = 1;
31 sit->check_fd = 0;
32 if (sit->loaded >= sit->bufsize)
33 return;
34 sit->check_fd = 1;
35 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
36 }
37
38 static void stdin_default_event_handler(struct task *t)
39 {
40 PARA_NOTICE_LOG("%p: %s\n", t, PARA_STRERROR(-t->ret));
41 unregister_task(t);
42 }
43
44 /**
45 * the post select function of the stdin task
46 *
47 * \param s the scheduler this task was registered to
48 * \param t the task structure of the stdin task
49 *
50 * This function checks if \p STDIN_FILENO was included by in the read fd set
51 * of \a s during the previous pre_select call. If yes, and \p STDIN_FILENO
52 * appeears to be readable, data is read from stdin into the buffer of the
53 * stdin task.
54 */
55 void stdin_post_select(struct sched *s, struct task *t)
56 {
57 struct stdin_task *sit = t->private_data;
58 ssize_t ret;
59
60 t->ret = 1;
61 if (!sit->check_fd)
62 return;
63 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
64 return;
65 ret = read(STDIN_FILENO, sit->buf + sit->loaded, sit->bufsize - sit->loaded);
66 if (ret < 0)
67 t->ret = -E_STDIN_READ;
68 else if (ret > 0) {
69 sit->loaded += ret;
70 t->ret = ret;
71 } else
72 t->ret = -E_STDIN_EOF;
73 if (t->ret < 0)
74 sit->eof = 1;
75 }
76
77 /**
78 * initialize a stdin task structure with default values
79 *
80 * \param sit the stdin task structure
81 *
82 * This fills in the pre/post select function poinzters of the task structure
83 * given by \a sot. It also sets up a default error handler which unregisters
84 * the task. Moreover, \a loaded and \a eof are set to zero and \a bufsize is
85 * initialized to 16 KB (but no buffer is allocated).
86 */
87 void stdin_set_defaults(struct stdin_task *sit)
88 {
89 sit->bufsize = 16 * 1024,
90 sit->loaded = 0,
91 sit->eof = 0,
92 sit->task.pre_select = stdin_pre_select;
93 sit->task.post_select = stdin_post_select;
94 sit->task.event_handler = stdin_default_event_handler;
95 sit->task.private_data = sit;
96 mark_fd_nonblock(STDIN_FILENO);
97 sprintf(sit->task.status, "stdin reader");
98 }