-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutil.h
104 lines (93 loc) · 1.49 KB
/
util.h
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
100
101
102
103
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#define log_debug(fmt, args...) \
fprintf(stderr, "%s(%d): " fmt "\n", __FILE__, __LINE__, ##args)
class FIFO
{
public:
FIFO(const std::string &path);
~FIFO();
int read(char *buf, int len);
int write(char *buf, int len);
private:
int fd;
std::string path;
int open(mode_t mode);
};
FIFO::FIFO(const std::string &path){
signal(SIGPIPE, SIG_IGN);
fd = -1;
this->path = path;
}
FIFO::~FIFO(){
if(fd >= 0){
close(fd);
fd = -1;
}
}
int FIFO::open(mode_t mode){
const char *path = this->path.c_str();
if(mkfifo(path, mode) == -1 && errno != EEXIST){
return -1;
}
if(mode & O_WRONLY){
if(chmod(path, 0666) == -1){
return -1;
}
}
fd = ::open(path, O_RDWR | O_NONBLOCK);
if(fd == -1){
if(errno == ENXIO){
return 0;
}
return -1;
}
return 1;
}
int FIFO::read(char *buf, int len){
if(fd < 0){
this->open(O_RDONLY);
}
if(fd < 0){
return 0;
}
while(1){
int ret = ::read(fd, buf, len);
if(ret == -1){
if(errno == EAGAIN){
return 0;
}
return -1;
}
return ret;
}
}
int FIFO::write(char *buf, int len){
if(fd < 0){
this->open(O_WRONLY);
}
if(fd < 0){
return 0;
}
while(1){
int ret = ::write(fd, buf, len);
if(ret == -1){
if(errno == EINTR){
continue;
}
if(errno == EAGAIN){
return 0;
}
return -1;
}
return ret;
}
}