Move struct senders[] from server.c to vss.c.
[paraslash.git] / stdin.c
1 /*
2 * Copyright (C) 2006-2008 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 <dirent.h> /* readdir() */
10 #include <assert.h>
11
12
13 #include "para.h"
14 #include "string.h"
15 #include "list.h"
16 #include "sched.h"
17 #include "fd.h"
18 #include "error.h"
19 #include "stdin.h"
20
21 /**
22 * The pre_select function of the stdin task.
23 *
24 * \param s The scheduler this task was registered to.
25 * \param t The task structure of the stdin task.
26 *
27 * This function is always successful. If there is space left in the
28 * buffer of the stdin task, it adds \p STDIN_FILENO to the read fd set
29 * of \a s.
30 */
31 static void stdin_pre_select(struct sched *s, struct task *t)
32 {
33 struct stdin_task *sit = container_of(t, struct stdin_task, task);
34 t->error = 0;
35 sit->check_fd = 0;
36 if (sit->loaded >= sit->bufsize)
37 return;
38 sit->check_fd = 1;
39 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
40 }
41
42 /**
43 * The post select function of the stdin task.
44 *
45 * \param s The scheduler this task was registered to.
46 * \param t The task structure of the stdin task.
47 *
48 * This function checks if \p STDIN_FILENO was included by in the read fd set
49 * of \a s during the previous pre_select call. If yes, and \p STDIN_FILENO
50 * appears to be readable, data is read from stdin into the buffer of the
51 * stdin task.
52 */
53 static void stdin_post_select(struct sched *s, struct task *t)
54 {
55 struct stdin_task *sit = container_of(t, struct stdin_task, task);
56 ssize_t ret;
57
58 t->error = 0;
59 if (!sit->check_fd)
60 return;
61 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
62 return;
63 ret = read(STDIN_FILENO, sit->buf + sit->loaded, sit->bufsize - sit->loaded);
64 if (ret < 0)
65 t->error = ERRNO_TO_PARA_ERROR(errno);
66 else if (ret > 0)
67 sit->loaded += ret;
68 else
69 t->error = -E_STDIN_EOF;
70 }
71
72 /**
73 * Initialize a stdin task structure with default values.
74 *
75 * \param sit The stdin task structure.
76 *
77 * This fills in the pre/post select function pointers of the task structure
78 * given by \a sit. Moreover, the stdin file desctiptor is set to nonblocking
79 * mode and \a bufsize is initialized to 16 KB (but no buffer is allocated).
80 */
81 void stdin_set_defaults(struct stdin_task *sit)
82 {
83 int ret;
84
85 sit->bufsize = 16 * 1024,
86 sit->task.pre_select = stdin_pre_select;
87 sit->task.post_select = stdin_post_select;
88 sprintf(sit->task.status, "stdin reader");
89 ret = mark_fd_nonblocking(STDIN_FILENO);
90 if (ret >= 0)
91 return;
92 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
93 exit(EXIT_FAILURE);
94 }