-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsgQ.c
More file actions
84 lines (70 loc) · 1.73 KB
/
msgQ.c
File metadata and controls
84 lines (70 loc) · 1.73 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
// Colas de mensajes del System V
// MSG-Q - crea dos procesos sender (hijo) y receiver (padre)
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSG_KEY 1234
/* Define the message structure */
struct mymsg {
long mtype; /* Message type */
char mtext[1024]; /* Message content */
};
/* Sender process */
void sender() {
int msgid, ret;
struct mymsg msg;
/* Create or open the message queue */
msgid = msgget(MSG_KEY, IPC_CREAT | 0666);
if (msgid < 0) {
perror("msgget");
exit(1);
}
/* Construct the message */
msg.mtype = 1;
strncpy(msg.mtext, "Hello, waveshare!", 1024);
/* Send the message */
ret = msgsnd(msgid, &msg, sizeof(struct mymsg) - sizeof(long), 0);
if (ret < 0) {
perror("msgsnd");
exit(1);
}
printf("Sent message: %s\n", msg.mtext);
}
/* Receiver process */
void receiver() {
int msgid, ret;
struct mymsg msg;
/* Open the message queue */
msgid = msgget(MSG_KEY, IPC_CREAT | 0666);
if (msgid < 0) {
perror("msgget");
exit(1);
}
/* Receive the message */
ret = msgrcv(msgid, &msg, sizeof(struct mymsg) - sizeof(long), 1, 0);
if (ret < 0) {
perror("msgrcv");
exit(1);
}
printf("Received message: %s\n", msg.mtext);
}
int main(int argc, char *argv[]) {
pid_t pid;
/* Create a child process */
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
/* Child process acts as the sender */
sender();
} else {
/* Parent process acts as the receiver */
receiver();
}
return 0;
}