-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem-10
More file actions
52 lines (44 loc) · 1.43 KB
/
problem-10
File metadata and controls
52 lines (44 loc) · 1.43 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// Define the message structure
struct message {
long msg_type; // Message type
char msg_text[100]; // Message text
};
int main() {
// Generate a unique key for the message queue
key_t key = ftok("msgqfile", 65);
// Create a new message queue (or get the identifier of an existing one)
int msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
// Create a message structure
struct message msg;
msg.msg_type = 1; // Message type (can be any positive number)
// Producer: Send a message to the message queue
strcpy(msg.msg_text, "Hello, message queue!");
if (msgsnd(msgid, (void*)&msg, sizeof(msg.msg_text), IPC_NOWAIT) == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
printf("Producer: Data sent to message queue: %s\n", msg.msg_text);
// Consumer: Receive a message from the message queue
if (msgrcv(msgid, (void*)&msg, sizeof(msg.msg_text), 1, 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("Consumer: Data received from message queue: %s\n", msg.msg_text);
// Remove the message queue
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(EXIT_FAILURE);
}
return 0;
}