-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessage_queue_demo.cpp
More file actions
86 lines (77 loc) · 2.21 KB
/
Copy pathMessage_queue_demo.cpp
File metadata and controls
86 lines (77 loc) · 2.21 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
/*
A message queue manipulation utility
*/
#include "Message_que.h"
#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
typedef struct {
long int m_type;
char m_text[1024];
} MESSAGE;
extern char *optarg;
extern int optind, opterr, optopt;
int
main(int argc, char *argv[])
{
int c;
// Added 'n' (nondestructive read) and 'd' (delete queue)
char optstring[] = "sri:m:nd";
opterr = 0;
bool snd_msg = false, get_msg = false, rmv_que = false, peek_msg = false;
char *the_message;
// Allocate msg - clear text
MESSAGE my_msg;
memset(my_msg.m_text, 0x0, 1024);
// Allocate - acquire msg queue
Message_que MQ('M');
if (!MQ.Exist('M'))
MQ.Create();
else
MQ.Acquire();
// Process command line args
while ((c = getopt(argc, argv, optstring)) != -1)
switch (c) {
case 's':
snd_msg = true;
break;
case 'r':
get_msg = true;
break;
case 'n':
// nondestructive read (peek)
peek_msg = true;
break;
case 'd':
// remove the message queue
rmv_que = true;
break;
case 'i':
my_msg.m_type = atol(optarg);
break;
case 'm':
strcpy(my_msg.m_text, optarg);
break;
default:
break;
}
if (snd_msg && my_msg.m_type > 0) {
MQ.Enque(&my_msg, strlen(my_msg.m_text) + 1);
cerr << "Added : " << my_msg.m_text << endl;
} else if (get_msg && my_msg.m_type > 0) {
MQ.Deque(&my_msg, 1024, my_msg.m_type);
cerr << "Message: " << my_msg.m_text << endl;
} else if (peek_msg && my_msg.m_type > 0) {
int nbytes = MQ.Deque(&my_msg, 1024, my_msg.m_type);
cerr << "Message (peek): " << my_msg.m_text << endl;
// Re-enqueue the same message so it stays in the queue
MQ.Enque(&my_msg, nbytes);
} else if (rmv_que) {
MQ.Remove();
cerr << "Message queue removed" << endl;
} else {
cerr << "Invalid command line option(s)" << endl;
}
return 0;
}