Repository navigation
Expand file tree
/
Copy pathexample.cpp
More file actions
125 lines (94 loc) · 2.05 KB
/
Copy pathexample.cpp
File metadata and controls
125 lines (94 loc) · 2.05 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// -*- compile-command: "g++ example.cpp mqueue.cpp exception.cpp -lrt" -*-
#include "mqueue.hh"
#include <cstdlib>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cerrno>
#define PARENT const pid_t pid = fork(); string ID = "C"; if (pid) { ID = "P";
#define CHILD waitpid(pid, NULL, 0); } else
#define print(VAR) std::cout << #VAR" → " << VAR << std::endl;
#include <cstring>
void clear(void)
{
struct mq::attr attr;
const string name("/a");
PARENT
{
char buffer[attr.msgsize];
unsigned int priority;
struct mq mq;
mq.open(name, O_CREAT | O_RDONLY, S_IRUSR | S_IWUSR, attr);
mq.receive(buffer, attr.msgsize, &priority);
mq.close();
mq.unlink();
print(buffer); print(priority);
}
CHILD
{
struct mq mq;
mq.open(name, O_WRONLY);
mq.send("clear ", 3);
mq.close();
}
}
void simple(void)
{
struct mq::attr attr;
const string name("/a");
PARENT
{
char buffer[attr.msgsize];
unsigned int priority;
struct mq mq("", O_CREAT | O_RDONLY, S_IRUSR | S_IWUSR, attr);
mq.receive(buffer, attr.msgsize, &priority);
print(buffer); print(priority);
}
CHILD
{
struct mq mq(name, O_WRONLY);
mq.send(string("simple"), 0);
exit(EXIT_SUCCESS);
}
}
struct handle
{
static const size_t sizeof_name = 32;
int pid;
char name[sizeof_name];
handle(void)
{ }
handle(int pid, const string& name) : pid(pid)
{
::strncpy(this->name, name.c_str(), sizeof_name);
}
};
#include <mqueue.h>
int main(int argc, const char *argv[])
{
const string name(argv[1] ?: "/a");
struct mq::attr attr;
int fd;
print(name);
attr.flags = O_NONBLOCK;
attr.msgsize = sizeof(struct handle);
PARENT
{
struct mq mq(name, O_CREAT | O_RDONLY, S_IRUSR | S_IWUSR, attr);
struct handle dst;
mq.receive(dst);
print(dst.pid);
print(dst.name);
mq.unlink();
}
CHILD
{
struct mq mq(name, O_WRONLY);
struct handle src(42, "ça marche");
mq.send(src, 5);
write(mq, "", 0);
exit(EXIT_SUCCESS);
}
return EXIT_SUCCESS;
}