-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfifo_token_ring.c
More file actions
64 lines (57 loc) · 1.91 KB
/
Copy pathfifo_token_ring.c
File metadata and controls
64 lines (57 loc) · 1.91 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
// Compile: gcc -o fifo_token_ring fifo_token_ring.c
// Run: ./fifo_token_ring N rounds
// Example: ./fifo_token_ring 4 3
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#if defined(__has_include)
# if __has_include(<sys/wait.h>)
# include <sys/wait.h>
# endif
#elif defined(__unix__) || defined(__APPLE__)
# include <sys/wait.h>
#endif
#include <string.h>
#define MAXFN 64
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]);
char names[N][MAXFN];
for(int i=0;i<N;i++) snprintf(names[i],MAXFN,"/tmp/fifo_ring_%d",i);
// create FIFOs
for(int i=0;i<N;i++){
mkfifo(names[i], 0666);
}
for(int i=0;i<N;i++){
pid_t pid = fork();
if(pid<0){ perror("fork"); exit(1); }
if(pid==0){
int read_fd = open(names[i], O_RDONLY);
int write_fd = open(names[(i+1)%N], O_WRONLY);
if(read_fd<0||write_fd<0){ perror("open fifo"); exit(1); }
while(1){
int token;
ssize_t r = read(read_fd, &token, sizeof(int));
if(r<=0) break;
printf("Proc %d pid %d got token=%d\n", i, getpid(), token);
fflush(stdout);
token++;
if(write(write_fd, &token, sizeof(int))<=0) break;
}
close(read_fd); close(write_fd);
_exit(0);
}
}
// parent: open one FIFO for writing to start the token (to FIFO 0)
int start_fd = open(names[0], O_WRONLY);
if(start_fd<0){ perror("open start"); }
int token = 0, maxToken = N*rounds;
if(write(start_fd, &token, sizeof(int))<=0) perror("start write");
close(start_fd);
sleep(1 + rounds * N / 10 + 1);
for(int i=0;i<N;i++) unlink(names[i]);
for(int i=0;i<N;i++) wait(NULL);
return 0;
}