-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcashier.c
More file actions
252 lines (214 loc) · 8.2 KB
/
cashier.c
File metadata and controls
252 lines (214 loc) · 8.2 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#define _GNU_SOURCE
#include "constants.h"
#include "ipc/messages.h"
#include "ipc/ipc.h"
#include "core/logger.h"
#include "core/time_sim.h"
#include "common/signal_common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/msg.h>
#include <time.h>
static int g_running = 1;
// Use macro-generated signal handler for basic shutdown handling
DEFINE_BASIC_SIGNAL_HANDLER(signal_handler)
/**
* @brief Calculate ticket expiration time in simulated minutes.
*
* @param state Shared state with ticket duration settings.
* @param ticket Type of ticket being purchased.
* @return Expiration time in simulated minutes from midnight.
*/
static int calculate_ticket_validity(SharedState *state, TicketType ticket) {
int current_minutes = time_get_sim_minutes(state);
switch (ticket) {
case TICKET_SINGLE:
return state->sim_end_minutes; // Valid all day (single use)
case TICKET_TIME_T1:
return current_minutes + state->ticket_t1_duration;
case TICKET_TIME_T2:
return current_minutes + state->ticket_t2_duration;
case TICKET_TIME_T3:
return current_minutes + state->ticket_t3_duration;
case TICKET_DAILY:
return state->sim_end_minutes;
default:
return state->sim_end_minutes;
}
}
/**
* @brief Calculate ticket price for one person.
*
* Age discounts: under 10 years or 65+ get 25% off.
*
* @param age Tourist age in years.
* @param ticket Type of ticket being purchased.
* @param is_vip Whether tourist has VIP status (adds surcharge).
* @return Price in PLN.
*/
static int calculate_price(int age, TicketType ticket, int is_vip) {
// Base prices
int base_prices[] = {15, 30, 50, 70, 80};
int price = base_prices[ticket];
// VIP surcharge
if (is_vip) {
price += 50;
}
// Age discounts
if (age < 10) {
price = (price * 75) / 100; // 25% discount
} else if (age >= 65) {
price = (price * 75) / 100; // 25% discount
}
return price;
}
/**
* @brief Calculate total family ticket price.
*
* Parent and kids all get the same ticket type.
* Kids (4-7 years old) always get the under-10 discount.
*
* @param parent_age Parent's age in years.
* @param ticket Type of ticket for the family.
* @param is_vip Whether family has VIP status.
* @param kid_count Number of children (0-2).
* @return Total price in PLN for entire family.
*/
static int calculate_family_price(int parent_age, TicketType ticket, int is_vip,
int kid_count) {
// Parent ticket
int total = calculate_price(parent_age, ticket, is_vip);
// Kid tickets - all kids are 4-7 years old, so always get under-10 discount
// Use age 5 as representative kid age (any value < 10 works)
for (int i = 0; i < kid_count; i++) {
total += calculate_price(5, ticket, 0);
}
return total;
}
/**
* @brief Cashier process entry point.
*
* Handles ticket sales via message queue. Calculates prices with age discounts
* and VIP surcharges. Runs until station closes or shutdown signal received.
*
* @param res IPC resources (message queues, semaphores, shared memory).
* @param keys IPC keys (unused, kept for interface consistency).
*/
void cashier_main(IPCResources *res, IPCKeys *keys) {
(void)keys;
// Initialize logger with component type
logger_init(res->state, LOG_CASHIER);
logger_set_debug_enabled(res->state->debug_logs_enabled);
// Install signal handlers
struct sigaction sa;
sa.sa_handler = signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Seed random number generator
srand(time(NULL) ^ getpid());
// Signal that this worker is ready (startup barrier)
if (ipc_signal_worker_ready(res) == -1) {
log_error("CASHIER", "Failed to signal ready, exiting");
return;
}
log_info("CASHIER", "Cashier ready to serve tourists");
while (g_running && res->state->running) {
// Check if closing
if (res->state->closing) {
log_info("CASHIER", "Station closing, no more tickets");
break;
}
// Wait for ticket request (only receive requests, not responses)
CashierMsg request;
ssize_t ret = msgrcv(res->mq_cashier_id, &request, sizeof(request) - sizeof(long),
MSG_CASHIER_REQUEST, 0);
if (ret == -1) {
if (errno == EINTR) {
continue; // Interrupted by signal
}
if (errno == EIDRM) {
log_debug("CASHIER", "Message queue removed, exiting");
break;
}
perror("cashier: msgrcv");
continue;
}
// Check again if closing
if (res->state->closing) {
log_info("CASHIER", "Station closing, refusing ticket for tourist %d", request.tourist_id);
// Send rejection (mtype = response base + tourist_id, ticket_type = -1)
CashierMsg response = request;
response.mtype = MSG_CASHIER_RESPONSE_BASE + request.tourist_id;
response.ticket_type = -1;
if (msgsnd(res->mq_cashier_id, &response, sizeof(response) - sizeof(long), 0) == -1) {
if (errno == EIDRM) break;
if (errno != EINTR) perror("cashier: msgsnd rejection");
}
continue;
}
// Use ticket type requested by tourist
TicketType ticket = request.ticket_type;
int valid_until = calculate_ticket_validity(res->state, ticket);
// Calculate price for whole family
int price;
if (request.kid_count > 0) {
price = calculate_family_price(request.age, ticket, request.is_vip,
request.kid_count);
} else {
price = calculate_price(request.age, ticket, request.is_vip);
}
// Update statistics (count parent + kids as separate tourists)
if (sem_wait_pauseable(res, SEM_STATS, 1) == -1) {
continue; // Check loop condition on failure
}
res->state->total_tourists += (1 + request.kid_count);
res->state->tourists_by_ticket[ticket] += (1 + request.kid_count);
sem_post(res->sem_id, SEM_STATS, 1);
// Send ticket response (mtype = response base + tourist_id)
CashierMsg response = request;
response.mtype = MSG_CASHIER_RESPONSE_BASE + request.tourist_id;
response.ticket_type = ticket;
response.ticket_valid_until = valid_until;
if (msgsnd(res->mq_cashier_id, &response, sizeof(response) - sizeof(long), 0) == -1) {
if (errno == EINTR) continue;
if (errno == EIDRM) {
log_debug("CASHIER", "Message queue removed during send");
break;
}
perror("cashier: msgsnd ticket");
continue;
}
const char *ticket_names[] = {"SINGLE", "TIME_T1", "TIME_T2", "TIME_T3", "DAILY"};
const char *type_names[] = {"walker", "cyclist", "family"};
const char *type_name = type_names[request.tourist_type];
char valid_buf[8];
time_format_minutes(valid_until, valid_buf, sizeof(valid_buf));
if (request.kid_count > 0) {
log_info("CASHIER", "Sold %s family ticket to tourist %d (%s, age %d%s) + %d kid(s) - valid until %s, price %d PLN",
ticket_names[ticket],
request.tourist_id,
type_name,
request.age,
request.is_vip ? ", VIP" : "",
request.kid_count,
valid_buf,
price);
} else {
log_info("CASHIER", "Sold %s ticket to tourist %d (%s, age %d%s) - valid until %s, price %d PLN",
ticket_names[ticket],
request.tourist_id,
type_name,
request.age,
request.is_vip ? ", VIP" : "",
valid_buf,
price);
}
}
log_info("CASHIER", "Cashier shutting down");
}