-
Notifications
You must be signed in to change notification settings - Fork 0
/
comunication.cpp
105 lines (92 loc) · 2.37 KB
/
comunication.cpp
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 "comunication.hpp"
#include <iostream>
MessageQueue::MessageQueue(QueueType type_arg,int key,int flags){
qKey = key;
qFlags = flags;
type = type_arg;
Owner = false;
Buffer.mtype = 1;
Created = false;
//Solicita fila de mensagens com key e flags definidas
if (qFlags|IPC_CREAT){
Owner = true;
}
MessageQueueId = msgget(qKey, qFlags);
if (MessageQueueId < 0){
//Falha
std::cout << MessageQueueId << "]\n";
Working = false;
}else{
Created = true;
Working = true;
}
}
MessageQueue::~MessageQueue(){}
void MessageQueue::Close(){
if (Created){
if (msgctl(MessageQueueId, IPC_RMID, NULL) == 0){
Created = false;
}else{
std::cout << "[Error] Cannot delete!\n";
}
}
}
//Polimorfismo
bool MessageQueue::Send(std::string str){
const char *c = str.c_str();
return Send(c,str.size()+1);
}
bool MessageQueue::Send(const char *message,int size){
return Send((char*)message,size);
}
bool MessageQueue::Send(char *message,int size){
if (!isSender()){
std::cout << "[Error] I am not sender!\n";
return false;
}
if (size > MSG_SIZE){
std::cout << "[Error] Message too big\n";
return false;
}
//Copy
for (int i=0;i<size;i++){
Buffer.mtext[i] = message[i];
}
if (msgsnd(MessageQueueId, &Buffer, size, 0) < 0) {
return false;
}
return true;
}
std::string MessageQueue::Receive(bool wait){
std::string msg = "";
Receive(msg,wait);
return msg;
}
bool MessageQueue::Receive(std::string &str,bool wait){
char message[MSG_SIZE];
if (!Receive(message,wait)){
return false;
}
std::string data = message;
str = data;
return true;
}
bool MessageQueue::Receive(char *message,bool wait){
if (!isWorking()){
std::cout << "[Error] Not working!\n";
return false;
}
if (!isReceiver()){
std::cout << "[Error] I am not receiver! ["<<type<<"]\n";
return false;
}
int readSize=-1;
if (readSize = msgrcv(MessageQueueId, &Buffer, MSG_SIZE, 1,(wait ? 0 : IPC_NOWAIT) ) < 0){
return false;
}
LastReadSize = readSize;
for (int i=0;i<MSG_SIZE+1;i++){
message[i] = Buffer.mtext[i];
}
return true;
}