-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprg_io_nonblock.c
80 lines (69 loc) · 2.21 KB
/
prg_io_nonblock.c
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
/*
* Filename: prg_io_nonblock.c
* Date: 2019/12/25 14:20
* Author: Jan Faigl
*/
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include <poll.h>
#include "prg_io_nonblock.h"
/// ----------------------------------------------------------------------------
static int io_open(const char *fname, int flag)
{
int fd = open(fname, flag | O_NOCTTY | O_SYNC);
if (fd != -1) {
// Set fd to non block mode
int flags = fcntl(fd, F_GETFL);
flags &= ~O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0) {
fprintf(stderr, "Error in %s(), file %s, line: %d, errno %d\n", __func__, __FILE__, __LINE__, errno);
}
}
return fd;
}
/// ----------------------------------------------------------------------------
int io_open_read(const char *fname)
{
// as defined for FIFO, open will be blocked for read only unless nonblock is specified
return io_open(fname, O_RDONLY | O_NONBLOCK);
}
/// ----------------------------------------------------------------------------
int io_open_write(const char *fname)
{
// Be aware that the opening named pipe for writing is blocked until the pipe is opened for reading.
// Thus, run a program that opens the pipe or call, e.g., 'tail -f fname', where 'fname' is the filename name of the named pipe being opened for writing.
return io_open(fname, O_WRONLY);
}
/// ----------------------------------------------------------------------------
int io_close(int fd)
{
return close(fd);
}
/// ----------------------------------------------------------------------------
int io_putc(int fd, char c)
{
return write(fd, &c, 1);
}
/// ----------------------------------------------------------------------------
int io_getc(int fd)
{
char c;
int r = read(fd, &c, 1);
return r == 1 ? c : -1;
}
/// ----------------------------------------------------------------------------
int io_getc_timeout(int fd, int timeout_ms, unsigned char *c)
{
struct pollfd ufdr[1];
int r = 0;
ufdr[0].fd = fd;
ufdr[0].events = POLLIN | POLLRDNORM;
if ((poll(&ufdr[0], 1, timeout_ms) > 0) && (ufdr[0].revents & (POLLIN | POLLRDNORM))) {
r = read(fd, c, 1);
}
return r;
}
/* end of prg_io_nonblock.c */