-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_queue_token_ring.c
More file actions
55 lines (49 loc) · 1.61 KB
/
Copy pathmessage_queue_token_ring.c
File metadata and controls
55 lines (49 loc) · 1.61 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
// Compile: gcc -o mq_token_ring mq_token_ring.c
// Run: ./mq_token_ring N rounds
// Example: ./mq_token_ring 4 3
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <sys/wait.h>
struct msgbuf {
long mtype;
int token;
};
int main(int argc,char **argv){
if(argc!=3){ fprintf(stderr,"Usage: %s N rounds\n",argv[0]); return 1;}
int N = atoi(argv[1]), rounds = atoi(argv[2]);
key_t key = ftok(".", 'T');
int msqid = msgget(key, IPC_CREAT | 0666);
if(msqid < 0){ perror("msgget"); exit(1); }
for(int i=0;i<N;i++){
pid_t pid = fork();
if(pid<0){ perror("fork"); exit(1); }
if(pid==0){
while(1){
struct msgbuf mb;
// receive messages of type = my id + 1 (msg types must be >0)
if(msgrcv(msqid, &mb, sizeof(int), i+1, 0) < 0) break;
printf("Proc %d (pid %d) got token=%d\n", i, getpid(), mb.token);
fflush(stdout);
mb.token++;
// send to next: type = (i+1)%N +1
mb.mtype = ( (i+1)%N ) + 1;
if(msgsnd(msqid, &mb, sizeof(int), 0) < 0) break;
}
_exit(0);
}
}
// parent starts token by sending type 1 (to process 0)
struct msgbuf mb;
mb.mtype = 1;
mb.token = 0;
if(msgsnd(msqid, &mb, sizeof(int), 0) < 0) perror("start msgsnd");
// naive termination: allow some time then remove the queue
sleep(1 + rounds * N / 10 + 1);
// cleanup
msgctl(msqid, IPC_RMID, NULL);
for(int i=0;i<N;i++) wait(NULL);
return 0;
}