-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.c
120 lines (100 loc) · 2.07 KB
/
client.c
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
/*
* client.c
*
* a standalone client for the timeserver
* only for testing; for real programs:
* timeexec program args...
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/msg.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include "timecontrol.h"
void handler(int sig) {
(void) sig;
}
int main() {
int queue;
key_t key;
int res;
long client;
srandom(time(NULL) + getpid());
signal(SIGINT, handler);
/* open queue */
key = ftok(KEYFILE, TIMESERVER);
if (key == -1) {
perror(KEYFILE);
exit(EXIT_FAILURE);
}
queue = msgget(key, 0700);
if (queue == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
/* obtain client number */
msg.mtype = REGISTER;
res = msgsnd(queue, &msg, msgsize, 0);
if (res == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
res = msgrcv(queue, &msg, msgsize, CLIENTID, 0);
if (res == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
client = msg.client;
printf("client: %ld\n", client);
if (client == -1) {
printf("cannot register\n");
exit(EXIT_FAILURE);
}
/* sleep */
msg.mtype = SLEEP;
msg.client = client;
msg.time = random() % 100;
printf("sleep(%ld)\n", msg.time);
res = msgsnd(queue, &msg, msgsize, 0);
if (res == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
printf("sleep\n");
res = msgrcv(queue, &msg, msgsize, WAKE(client), 0);
if (res == -1) {
perror("msgrcv");
if (errno != EINTR)
exit(EXIT_FAILURE);
msg.mtype = CANCEL;
msg.client = client;
msgsnd(queue, &msg, msgsize, 0);
msgrcv(queue, &msg, msgsize, WAKE(client), 0);
}
printf("sleep done\n");
/* query time */
msg.mtype = QUERY;
msg.client = client;
res = msgsnd(queue, &msg, msgsize, 0);
if (res == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
res = msgrcv(queue, &msg, msgsize, TIME, 0);
if (res == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("time: %ld\n", msg.time);
/* unregister */
msg.mtype = UNREGISTER;
msg.time = client;
res = msgsnd(queue, &msg, msgsize, 0);
if (res == -1) {
perror("msgsnd");
exit(EXIT_FAILURE);
}
return 0;
}