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
104
105
106
107
108
|
/*
* Recitation Section Number: 02
* Breakout Number: 05
* Graden Hill (hill1582)
* Gustav Baumgart (baumg260)
* Matt Strapp (strap012)
* Skylan Recnana (recan001)
*/
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include <zconf.h>
#include <string.h>
#include <stdlib.h>
#define PERM 0666
#define MSGSIZE 100
#define NCHILD 3
// structure for message queue
typedef struct msg_buffer {
long mtype;
char mtext[MSGSIZE];
} message;
int main(void) {
key_t key;
int msgid;
pid_t pid1, pid2;
message msg;
// generate unique key
key = ftok("recitation", 4061);
// creates a message queue
msgid = msgget(key, PERM | IPC_CREAT);
// sender child process
pid1 = fork();
if (pid1 == 0) {
for (int i = 0; i < NCHILD; i++) {
msg.mtype = 111;
memset(msg.mtext, '\0', MSGSIZE);
sprintf(msg.mtext, "Hello child %d", i);
// send message to other child processes
msgsnd(msgid, &msg, MSGSIZE, 0);
// display the message
printf("[%d] Data sent is : %s \n", i, msg.mtext);
}
for (int i = 0; i < NCHILD; i++) {
msg.mtype = 222;
memset(msg.mtext, '\0', MSGSIZE);
sprintf(msg.mtext, "Message %d", i);
// send message to other child processes
msgsnd(msgid, &msg, MSGSIZE, 0);
// display the message
printf("[%d] Data sent is : %s \n", i, msg.mtext);
}
for (int i = 0; i < NCHILD; i++) {
msg.mtype = 333;
memset(msg.mtext, '\0', MSGSIZE);
sprintf(msg.mtext, "Bye %d", i);
// send message to other child processes
msgsnd(msgid, &msg, MSGSIZE, 0);
// display the message
printf("[%d] Data sent is : %s \n", i, msg.mtext);
}
exit(0);
} else if (pid1 < 0) {
printf("fork1 error\n");
return -1;
}
// receiver child processes
for (int j = 0; j < NCHILD; j++) {
if ((pid2 = fork()) == 0) {
// receive message
msgrcv(msgid, &msg, MSGSIZE, 222, 0);
// display the message
printf("[%d] Data received is : %s \n", j, msg.mtext);
exit(0);
} else if (pid2 < 0) {
printf("fork2 error\n");
return -1;
}
}
while (wait(NULL) > 0);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
|