|
1 /** |
|
2 * Relational pipes |
|
3 * Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info) |
|
4 * |
|
5 * This program is free software: you can redistribute it and/or modify |
|
6 * it under the terms of the GNU General Public License as published by |
|
7 * the Free Software Foundation, version 3 of the License. |
|
8 * |
|
9 * This program is distributed in the hope that it will be useful, |
|
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 * GNU General Public License for more details. |
|
13 * |
|
14 * You should have received a copy of the GNU General Public License |
|
15 * along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
16 */ |
|
17 #pragma once |
|
18 |
|
19 #include <mqueue.h> |
|
20 #include <string> |
|
21 #include <stdexcept> |
|
22 #include <cstring> |
|
23 |
|
24 namespace relpipe { |
|
25 namespace in { |
|
26 namespace posixmq { |
|
27 |
|
28 class PosixMQ { |
|
29 private: |
|
30 size_t MSG_SIZE = 8192; // TODO: configurable/dynamic |
|
31 std::string queueName; |
|
32 mqd_t handle = -2; |
|
33 |
|
34 PosixMQ(std::string queueName, mqd_t handle) : queueName(queueName), handle(handle) { |
|
35 } |
|
36 |
|
37 public: |
|
38 |
|
39 virtual ~PosixMQ() { |
|
40 if (handle >= 0) mq_close(handle); |
|
41 } |
|
42 |
|
43 static PosixMQ* open(std::string queueName) { |
|
44 mqd_t handle = mq_open(queueName.c_str(), O_RDONLY | O_CREAT); |
|
45 if (handle >= 0) return new PosixMQ(queueName, handle); |
|
46 else throw std::logic_error("Unable to open PosixMQ: " + queueName + " error: " + strerror(errno)); |
|
47 } |
|
48 |
|
49 std::string receive() { |
|
50 char buffer[MSG_SIZE + 1]; |
|
51 memset(buffer, 0, MSG_SIZE + 1); |
|
52 ssize_t msgSize = mq_receive(handle, buffer, MSG_SIZE, nullptr); |
|
53 |
|
54 if (msgSize >= 0) return std::string(buffer); |
|
55 else throw std::logic_error("Unable to receive PosixMQ message from " + queueName + " error: " + strerror(errno)); |
|
56 } |
|
57 |
|
58 void unlink() { |
|
59 mq_unlink(queueName.c_str()); |
|
60 } |
|
61 |
|
62 }; |
|
63 |
|
64 } |
|
65 } |
|
66 } |