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
109
110
111
112
113
114
115
116
117
118
119
|
/* b01902062 藍挺瑋 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "logger.h"
#include "xwrap.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct {
pid_t pid;
int read;
int write;
} JudgeData;
typedef struct {
long score;
} PlayerData;
bool comb4 (Comp135* comp, int players[], long player_num) {
for (int i = 3; i >= 0; i--) {
if (players[i] + 1 <= player_num &&
players[i] + 1 + (3 - i) <= player_num) {
players[i]++;
for (int j = i + 1; j < 4; j++) {
players[j] = players[j - 1] + 1;
}
return true;
}
}
return false;
}
int main (int argc, char* argv[]) {
if (argc < 3) {
fprintf (stderr, "Usage: %s judge_num player_num\n", argv[0]);
return 1;
}
long judge_num, player_num;
if (xatol (argv[1], &judge_num) < 0) {
fprintf (stderr, "%s: `%s\' is not a number\n", argv[0], argv[1]);
return 2;
}
if (judge_num < 0) {
fprintf (stderr, "%s: judge_num must be a positive number\n", argv[0]);
return 3;
}
if (xatol (argv[2], &player_num) < 0) {
fprintf (stderr, "%s: `%s\' is not a number\n", argv[0], argv[2]);
return 2;
}
if (player_num < 4) {
fprintf (stderr, "%s: player_num must be greater than 4\n", argv[0]);
return 3;
}
Comp135 comp_struct, *comp;
comp = &comp_struct;
comp135_init (comp, argv[0], false);
JudgeData* jd = xmalloc (sizeof (JudgeData) * judge_num);
PlayerData* pd = xmalloc (sizeof (PlayerData) * player_num);
for (int i = 0; i < player_num; i++) {
pd[i].score = 0;
}
for (int i = 0; i < judge_num; i++) {
int fdr[2], fdw[2];
if (pipe (fdr) < 0) {
fprintf (stderr, "%s: pipe: %s\n", argv[0], strerror (errno));
return 4;
}
if (pipe (fdw) < 0) {
fprintf (stderr, "%s: pipe: %s\n", argv[0], strerror (errno));
return 4;
}
jd[i].pid = fork ();
if (jd[i].pid < 0) {
fprintf (stderr, "%s: fork: %s\n", argv[0], strerror (errno));
return 5;
} else if (jd[i].pid > 0) {
close (fdr[1]);
close (fdw[0]);
} else {
close (fdr[0]);
close (fdw[1]);
char* myjudge = xgetres ("judge");
execl (myjudge, "judge", xsprintf ("%d", i + 1), (char*)NULL);
fprintf (stderr, "%s: execl: %s: %s\n", argv[0], myjudge, strerror (errno));
_exit (1);
}
jd[i].read = fdr[0];
jd[i].write = fdw[1];
comp135_log (comp, "Judge %d created: PID = %u, read = %d, write = %d",
i + 1, jd[i].pid, jd[i].read, jd[i].write);
}
int players[4] = {1, 2, 3, 4};
do {
} while (comb4 (comp, players, player_num));
comp135_destroy (comp);
return 0;
}
|