fd.c
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Copyright (C) 2013 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup posix
* @{
* @file
* @brief Providing unifying file descriptor wrapper for POSIX-compliant
* operations.
* @author Christian Mehlis <mehlis@inf.fu-berlin.de>
* @author Martine Lenders <mlenders@inf.fu-berlin.de>
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unistd.h"
#include "fd.h"
#ifdef CPU_MSP430
#define FD_MAX 5
#else
#define FD_MAX 15
#endif
static fd_t fd_table[FD_MAX];
int fd_init(void)
{
memset(fd_table, 0, sizeof(fd_t) * FD_MAX);
return FD_MAX;
}
static int fd_get_next_free(void)
{
for (int i = 0; i < FD_MAX; i++) {
fd_t *cur = &fd_table[i];
if (!cur->internal_active) {
return i;
}
}
return -1;
}
int fd_new(int internal_fd, ssize_t (*internal_read)(int, void *, size_t),
ssize_t (*internal_write)(int, const void *, size_t),
int (*internal_close)(int))
{
int fd = fd_get_next_free();
if (fd >= 0) {
fd_t *fd_s = fd_get(fd);
fd_s->internal_active = 1;
fd_s->internal_fd = internal_fd;
fd_s->read = internal_read;
fd_s->write = internal_write;
fd_s->close = internal_close;
}
else {
errno = ENFILE;
return -1;
}
return fd;
}
fd_t *fd_get(int fd)
{
if (fd >= 0 && fd < FD_MAX) {
return &fd_table[fd];
}
return NULL;
}
void fd_destroy(int fd)
{
fd_t *cur = fd_get(fd);
if (!cur) {
return;
}
memset(cur, 0, sizeof(fd_t));
}
/**
* @}
*/