final 5
This commit is contained in:
113
lab_5/server.c
113
lab_5/server.c
@@ -1,38 +1,47 @@
|
|||||||
#define _GNU_SOURCE
|
#define _GNU_SOURCE // для определения расширенных возможностей glibc
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <mqueue.h>
|
#include <mqueue.h> // POSIX очереди сообщений: mq_open, mq_send, mq_receive, mq_timedreceive
|
||||||
#include <signal.h>
|
#include <signal.h> // sig_atomic_t, signal, SIGINT
|
||||||
#include <stdbool.h>
|
#include <stdbool.h> // bool, true/false
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h> // printf, fprintf, perror
|
||||||
#include <stdlib.h>
|
#include <stdlib.h> // atoi, malloc/free при желании
|
||||||
#include <string.h>
|
#include <string.h> // memset, strncpy, strncmp
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h> // константы прав доступа к объектам ФС
|
||||||
#include <time.h>
|
#include <time.h> // clock_gettime, nanosleep, struct timespec
|
||||||
|
|
||||||
#include "common.h"
|
#include "common.h" // описания REQ_QUEUE, NAME_MAXLEN, req_msg_t, rep_msg_t и т.п.
|
||||||
|
|
||||||
#ifndef MAX_CLIENTS
|
#ifndef MAX_CLIENTS
|
||||||
#define MAX_CLIENTS 128
|
#define MAX_CLIENTS 128 // максимальное число клиентов, чьи очереди мы запомним
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Глобальный флаг остановки сервера по сигналу
|
||||||
static volatile sig_atomic_t stop_flag = 0;
|
static volatile sig_atomic_t stop_flag = 0;
|
||||||
|
// Обработчик SIGINT: просто выставляет флаг
|
||||||
static void on_sigint(int) { stop_flag = 1; }
|
static void on_sigint(int) { stop_flag = 1; }
|
||||||
|
|
||||||
|
// Удобная функция "уснуть" на ms миллисекунд
|
||||||
static void msleep(int ms) {
|
static void msleep(int ms) {
|
||||||
struct timespec ts = {.tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L};
|
struct timespec ts = {
|
||||||
|
.tv_sec = ms / 1000,
|
||||||
|
.tv_nsec = (ms % 1000) * 1000000L
|
||||||
|
};
|
||||||
nanosleep(&ts, NULL);
|
nanosleep(&ts, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Simple client registry (stores unique reply queue names) */
|
/* Простейший реестр клиентов: массив имён их ответных очередей */
|
||||||
static char clients[MAX_CLIENTS][NAME_MAXLEN];
|
static char clients[MAX_CLIENTS][NAME_MAXLEN];
|
||||||
static int client_count = 0;
|
static int client_count = 0;
|
||||||
|
|
||||||
|
// Добавляет имя очереди клиента в список, если его там ещё нет
|
||||||
static void add_client(const char *name) {
|
static void add_client(const char *name) {
|
||||||
if (!name || name[0] == '\0') return;
|
if (!name || name[0] == '\0') return;
|
||||||
|
// Проверка на дубликат
|
||||||
for (int i = 0; i < client_count; ++i) {
|
for (int i = 0; i < client_count; ++i) {
|
||||||
if (strncmp(clients[i], name, NAME_MAXLEN) == 0) return;
|
if (strncmp(clients[i], name, NAME_MAXLEN) == 0) return;
|
||||||
}
|
}
|
||||||
|
// Если есть место — копируем имя в массив
|
||||||
if (client_count < MAX_CLIENTS) {
|
if (client_count < MAX_CLIENTS) {
|
||||||
strncpy(clients[client_count], name, NAME_MAXLEN - 1);
|
strncpy(clients[client_count], name, NAME_MAXLEN - 1);
|
||||||
clients[client_count][NAME_MAXLEN - 1] = '\0';
|
clients[client_count][NAME_MAXLEN - 1] = '\0';
|
||||||
@@ -40,44 +49,55 @@ static void add_client(const char *name) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Send a STOP reply (granted=0) to all recorded clients */
|
/* Рассылает всем запомненным клиентам сообщение STOP (granted=0, remain=0) */
|
||||||
static void send_stop_to_clients(void) {
|
static void send_stop_to_clients(void) {
|
||||||
rep_msg_t stoprep;
|
rep_msg_t stoprep;
|
||||||
memset(&stoprep, 0, sizeof(stoprep));
|
memset(&stoprep, 0, sizeof(stoprep));
|
||||||
stoprep.granted = 0;
|
stoprep.granted = 0;
|
||||||
stoprep.remain = 0;
|
stoprep.remain = 0;
|
||||||
|
|
||||||
for (int i = 0; i < client_count; ++i) {
|
for (int i = 0; i < client_count; ++i) {
|
||||||
|
// Открываем очередь ответа клиента только на запись
|
||||||
mqd_t q = mq_open(clients[i], O_WRONLY);
|
mqd_t q = mq_open(clients[i], O_WRONLY);
|
||||||
if (q == (mqd_t) -1) {
|
if (q == -1) {
|
||||||
// best-effort: skip if cannot open
|
// Лучшая попытка: если открыть не удалось — просто пропускаем
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// Отправляем структуру-ответ без приоритета (0)
|
||||||
mq_send(q, (const char *) &stoprep, sizeof(stoprep), 0);
|
mq_send(q, (const char *) &stoprep, sizeof(stoprep), 0);
|
||||||
mq_close(q);
|
mq_close(q);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
int main(int argc, char **argv) {
|
||||||
|
// Ожидается: total_honey, portion, period_ms, starvation_ms
|
||||||
if (argc != 5) {
|
if (argc != 5) {
|
||||||
fprintf(stderr, "Usage: %s <total_honey> <portion> <period_ms> <starvation_ms>\n", argv[0]);
|
fprintf(stderr, "Usage: %s <total_honey> <portion> <period_ms> <starvation_ms>\n", argv[0]);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
int remain = atoi(argv[1]);
|
|
||||||
int portion = atoi(argv[2]);
|
// Разбираем параметры симуляции
|
||||||
int period_ms = atoi(argv[3]);
|
int remain = atoi(argv[1]); // сколько "мёда" всего
|
||||||
int starvation_ms = atoi(argv[4]);
|
int portion = atoi(argv[2]); // сколько Винни ест за один подход
|
||||||
|
int period_ms = atoi(argv[3]); // период "еды" в миллисекундах
|
||||||
|
int starvation_ms = atoi(argv[4]); // через сколько мс без еды считаем, что Винни умер с голоду
|
||||||
|
|
||||||
if (remain < 0 || portion <= 0 || period_ms <= 0 || starvation_ms < 0) {
|
if (remain < 0 || portion <= 0 || period_ms <= 0 || starvation_ms < 0) {
|
||||||
fprintf(stderr, "Bad args\n");
|
fprintf(stderr, "Bad args\n");
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// На всякий случай удаляем старую очередь запросов, если осталась
|
||||||
mq_unlink(REQ_QUEUE);
|
mq_unlink(REQ_QUEUE);
|
||||||
|
|
||||||
|
// Настроиваем атрибуты очереди запросов
|
||||||
struct mq_attr attr;
|
struct mq_attr attr;
|
||||||
memset(&attr, 0, sizeof(attr));
|
memset(&attr, 0, sizeof(attr));
|
||||||
attr.mq_maxmsg = 10; // ваш системный максимум = 10
|
attr.mq_maxmsg = 10; // максимум 10 сообщений в очереди
|
||||||
attr.mq_msgsize = sizeof(req_msg_t);
|
attr.mq_msgsize = sizeof(req_msg_t); // размер одного сообщения = размер структуры запроса
|
||||||
|
|
||||||
// Открываем общую очередь на O_RDWR: читаем заявки и посылаем STOP
|
// Открываем общую очередь запросов: создаём и даём читать/писать
|
||||||
|
// (читаем заявки и также сможем через неё послать STOP при желании)
|
||||||
mqd_t qreq = mq_open(REQ_QUEUE, O_CREAT | O_RDWR, 0666, &attr);
|
mqd_t qreq = mq_open(REQ_QUEUE, O_CREAT | O_RDWR, 0666, &attr);
|
||||||
if (qreq == (mqd_t) -1) {
|
if (qreq == (mqd_t) -1) {
|
||||||
perror("mq_open qreq");
|
perror("mq_open qreq");
|
||||||
@@ -85,30 +105,40 @@ int main(int argc, char **argv) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Для отладки выводим реальные атрибуты очереди
|
||||||
struct mq_attr got;
|
struct mq_attr got;
|
||||||
if (mq_getattr(qreq, &got) == 0) {
|
if (mq_getattr(qreq, &got) == 0) {
|
||||||
fprintf(stderr, "Server: q=%s maxmsg=%ld msgsize=%ld cur=%ld\n",
|
fprintf(stderr, "Server: q=%s maxmsg=%ld msgsize=%ld cur=%ld\n",
|
||||||
REQ_QUEUE, got.mq_maxmsg, got.mq_msgsize, got.mq_curmsgs);
|
REQ_QUEUE, got.mq_maxmsg, got.mq_msgsize, got.mq_curmsgs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Обработчик Ctrl+C: аккуратное завершение
|
||||||
signal(SIGINT, on_sigint);
|
signal(SIGINT, on_sigint);
|
||||||
|
|
||||||
fprintf(stderr, "Server: started remain=%d portion=%d period=%dms starve=%dms\n",
|
fprintf(stderr, "Server: started remain=%d portion=%d period=%dms starve=%dms\n",
|
||||||
remain, portion, period_ms, starvation_ms);
|
remain, portion, period_ms, starvation_ms);
|
||||||
|
|
||||||
|
// Инициализируем "текущее время" и моменты следующего приёма пищи / последней еды
|
||||||
struct timespec now;
|
struct timespec now;
|
||||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
long long next_eat_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec + (long long) period_ms * 1000000LL;
|
long long now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
||||||
long long last_feed_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
long long next_eat_ns = now_ns + (long long) period_ms * 1000000LL; // когда Винни в следующий раз ест
|
||||||
|
long long last_feed_ns = now_ns; // когда он ел в последний раз
|
||||||
|
|
||||||
req_msg_t req;
|
req_msg_t req; // буфер для входящего запроса
|
||||||
bool need_stop_broadcast = false;
|
bool need_stop_broadcast = false; // флаг: нужно ли разослать клиентам STOP
|
||||||
|
|
||||||
|
// Главный цикл сервера: обрабатываем запросы и "еду" до сигнала или окончания мёда
|
||||||
while (!stop_flag) {
|
while (!stop_flag) {
|
||||||
|
// Обновляем текущее время
|
||||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
long long now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
||||||
|
|
||||||
|
// Сколько мс до следующего приёма пищи
|
||||||
int sleep_ms = (int) ((next_eat_ns - now_ns) / 1000000LL);
|
int sleep_ms = (int) ((next_eat_ns - now_ns) / 1000000LL);
|
||||||
if (sleep_ms < 0) sleep_ms = 0;
|
if (sleep_ms < 0) sleep_ms = 0;
|
||||||
|
|
||||||
|
// Дедлайн для mq_timedreceive: ждём сообщение не дольше sleep_ms
|
||||||
struct timespec deadline = {
|
struct timespec deadline = {
|
||||||
.tv_sec = now.tv_sec + sleep_ms / 1000,
|
.tv_sec = now.tv_sec + sleep_ms / 1000,
|
||||||
.tv_nsec = now.tv_nsec + (sleep_ms % 1000) * 1000000L
|
.tv_nsec = now.tv_nsec + (sleep_ms % 1000) * 1000000L
|
||||||
@@ -118,10 +148,12 @@ int main(int argc, char **argv) {
|
|||||||
deadline.tv_nsec -= 1000000000L;
|
deadline.tv_nsec -= 1000000000L;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Пытаемся принять запрос до наступления дедлайна
|
||||||
ssize_t rd = mq_timedreceive(qreq, (char *) &req, sizeof(req), NULL, &deadline);
|
ssize_t rd = mq_timedreceive(qreq, (char *) &req, sizeof(req), NULL, &deadline);
|
||||||
if (rd >= 0) {
|
if (rd >= 0) {
|
||||||
|
// Успешно прочитали структуру запроса
|
||||||
if (req.want != 0) {
|
if (req.want != 0) {
|
||||||
/* record client's reply queue so we can notify it on shutdown */
|
// Регистрируем очередь ответа клиента, чтобы уметь послать ему STOP
|
||||||
add_client(req.replyq);
|
add_client(req.replyq);
|
||||||
|
|
||||||
rep_msg_t rep;
|
rep_msg_t rep;
|
||||||
@@ -129,12 +161,15 @@ int main(int argc, char **argv) {
|
|||||||
int grant = req.want;
|
int grant = req.want;
|
||||||
if (grant > remain) grant = remain;
|
if (grant > remain) grant = remain;
|
||||||
remain -= grant;
|
remain -= grant;
|
||||||
rep.granted = grant;
|
rep.granted = grant; // сколько реально дали
|
||||||
rep.remain = remain;
|
rep.remain = remain; // сколько осталось
|
||||||
} else {
|
} else {
|
||||||
|
// Мёд закончился — ничего не даём
|
||||||
rep.granted = 0;
|
rep.granted = 0;
|
||||||
rep.remain = 0;
|
rep.remain = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Открываем очередь ответа клиента и отправляем ему ответ
|
||||||
mqd_t qrep = mq_open(req.replyq, O_WRONLY);
|
mqd_t qrep = mq_open(req.replyq, O_WRONLY);
|
||||||
if (qrep != (mqd_t) -1) {
|
if (qrep != (mqd_t) -1) {
|
||||||
mq_send(qrep, (const char *) &rep, sizeof(rep), 0);
|
mq_send(qrep, (const char *) &rep, sizeof(rep), 0);
|
||||||
@@ -142,42 +177,54 @@ int main(int argc, char **argv) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (errno != ETIMEDOUT && errno != EAGAIN) {
|
} else if (errno != ETIMEDOUT && errno != EAGAIN) {
|
||||||
|
// Любая ошибка, кроме "таймаут" или "временно нет сообщений", логируется
|
||||||
perror("mq_timedreceive");
|
perror("mq_timedreceive");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// После приёма (или таймаута) обновляем текущее время и проверяем, пора ли Винни есть
|
||||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
||||||
|
|
||||||
if (now_ns >= next_eat_ns) {
|
if (now_ns >= next_eat_ns) {
|
||||||
if (remain > 0) {
|
if (remain > 0) {
|
||||||
|
// Винни ест свою порцию (или остаток, если мёда меньше порции)
|
||||||
int eat = portion;
|
int eat = portion;
|
||||||
if (eat > remain) eat = remain;
|
if (eat > remain) eat = remain;
|
||||||
remain -= eat;
|
remain -= eat;
|
||||||
last_feed_ns = now_ns;
|
last_feed_ns = now_ns;
|
||||||
fprintf(stderr, "Winnie eats %d, remain=%d\n", eat, remain);
|
fprintf(stderr, "Winnie eats %d, remain=%d\n", eat, remain);
|
||||||
} else {
|
} else {
|
||||||
if (starvation_ms > 0 && (now_ns - last_feed_ns) / 1000000LL >= starvation_ms) {
|
// Мёда нет: проверяем, не умер ли Винни с голоду (starvation_ms)
|
||||||
|
if (starvation_ms > 0 &&
|
||||||
|
(now_ns - last_feed_ns) / 1000000LL >= starvation_ms) {
|
||||||
fprintf(stderr, "Winnie starved, stopping\n");
|
fprintf(stderr, "Winnie starved, stopping\n");
|
||||||
need_stop_broadcast = true;
|
need_stop_broadcast = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Планируем следующий приём пищи через period_ms
|
||||||
next_eat_ns = now_ns + (long long) period_ms * 1000000LL;
|
next_eat_ns = now_ns + (long long) period_ms * 1000000LL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Если мёд закончился, надо будет всем сообщить STOP и завершаться
|
||||||
if (remain <= 0) {
|
if (remain <= 0) {
|
||||||
need_stop_broadcast = true;
|
need_stop_broadcast = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// При нормальном окончании (мёд закончился или Винни умер с голоду)
|
||||||
|
// посылаем всем клиентам STOP
|
||||||
if (need_stop_broadcast) {
|
if (need_stop_broadcast) {
|
||||||
fprintf(stderr, "Server: broadcasting STOP to clients\n");
|
fprintf(stderr, "Server: broadcasting STOP to clients\n");
|
||||||
send_stop_to_clients();
|
send_stop_to_clients();
|
||||||
msleep(100);
|
msleep(100); // даём клиентам время получить сообщение
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Закрываем и удаляем очередь запросов
|
||||||
mq_close(qreq);
|
mq_close(qreq);
|
||||||
mq_unlink(REQ_QUEUE);
|
mq_unlink(REQ_QUEUE);
|
||||||
|
|
||||||
fprintf(stderr, "Server: finished\n");
|
fprintf(stderr, "Server: finished\n");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,28 @@
|
|||||||
// worker.c
|
#define _GNU_SOURCE // для определения расширенных возможностей glibc
|
||||||
#define _GNU_SOURCE
|
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <mqueue.h>
|
#include <mqueue.h> // POSIX очереди сообщений: mq_open, mq_send, mq_receive
|
||||||
#include <signal.h>
|
#include <signal.h>
|
||||||
#include <stdbool.h>
|
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h> // fprintf, perror, dprintf
|
||||||
#include <stdlib.h>
|
#include <stdlib.h> // atoi, rand_r
|
||||||
#include <string.h>
|
#include <string.h> // memset, strncpy, snprintf
|
||||||
#include <sys/stat.h>
|
#include <sys/stat.h> // права для mq_open (0666)
|
||||||
#include <time.h>
|
#include <time.h> // time(), nanosleep, struct timespec
|
||||||
#include <unistd.h>
|
#include <unistd.h> // getpid, STDOUT_FILENO
|
||||||
|
|
||||||
#include "common.h"
|
#include "common.h" // REQ_QUEUE, NAME_MAXLEN, req_msg_t, rep_msg_t
|
||||||
|
|
||||||
|
// Пауза на заданное количество миллисекунд
|
||||||
static void msleep(int ms) {
|
static void msleep(int ms) {
|
||||||
struct timespec ts = {.tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L};
|
struct timespec ts = {
|
||||||
|
.tv_sec = ms / 1000,
|
||||||
|
.tv_nsec = (ms % 1000) * 1000000L
|
||||||
|
};
|
||||||
nanosleep(&ts, NULL);
|
nanosleep(&ts, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
int main(int argc, char **argv) {
|
||||||
|
// Ожидается один аргумент: сколько мёда пчела просит за раз
|
||||||
if (argc != 2) {
|
if (argc != 2) {
|
||||||
fprintf(stderr, "Usage: %s <bee_portion>\n", argv[0]);
|
fprintf(stderr, "Usage: %s <bee_portion>\n", argv[0]);
|
||||||
return 2;
|
return 2;
|
||||||
@@ -30,67 +33,89 @@ int main(int argc, char **argv) {
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PID пчелы и имя её личной очереди ответов
|
||||||
pid_t me = getpid();
|
pid_t me = getpid();
|
||||||
char replyq[NAME_MAXLEN];
|
char replyq[NAME_MAXLEN];
|
||||||
snprintf(replyq, sizeof(replyq), "/bee_%d", (int) me);
|
snprintf(replyq, sizeof(replyq), "/bee_%d", (int) me);
|
||||||
|
|
||||||
|
// На всякий случай удаляем старую очередь с таким именем
|
||||||
mq_unlink(replyq);
|
mq_unlink(replyq);
|
||||||
|
|
||||||
|
// Атрибуты очереди ответов (куда сервер будет слать rep_msg_t)
|
||||||
struct mq_attr attr;
|
struct mq_attr attr;
|
||||||
memset(&attr, 0, sizeof(attr));
|
memset(&attr, 0, sizeof(attr));
|
||||||
attr.mq_maxmsg = 10;
|
attr.mq_maxmsg = 10;
|
||||||
attr.mq_msgsize = sizeof(rep_msg_t);
|
attr.mq_msgsize = sizeof(rep_msg_t);
|
||||||
|
|
||||||
|
// Создаём очередь ответов пчелы, только для чтения
|
||||||
mqd_t qrep = mq_open(replyq, O_CREAT | O_RDONLY, 0666, &attr);
|
mqd_t qrep = mq_open(replyq, O_CREAT | O_RDONLY, 0666, &attr);
|
||||||
if (qrep == (mqd_t) -1) {
|
if (qrep == (mqd_t) -1) {
|
||||||
perror("mq_open reply");
|
perror("mq_open reply");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
mqd_t qreq = (mqd_t) -1;
|
// Открываем очередь запросов к серверу (общая очередь REQ_QUEUE)
|
||||||
|
mqd_t qreq = -1;
|
||||||
for (int i = 0; i < 50; i++) {
|
for (int i = 0; i < 50; i++) {
|
||||||
qreq = mq_open(REQ_QUEUE, O_WRONLY);
|
qreq = mq_open(REQ_QUEUE, O_WRONLY);
|
||||||
if (qreq != (mqd_t) -1) break;
|
if (qreq != -1) break; // удалось открыть — выходим из цикла
|
||||||
if (errno != ENOENT) {
|
if (errno != ENOENT) {
|
||||||
|
// другая ошибка, не "очередь ещё не создана"
|
||||||
perror("mq_open req");
|
perror("mq_open req");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
// Если сервер ещё не создал очередь (ENOENT) — подождать и попробовать снова
|
||||||
msleep(100);
|
msleep(100);
|
||||||
}
|
}
|
||||||
if (qreq == (mqd_t) -1) {
|
if (qreq == -1) {
|
||||||
|
// Не смогли открыть очередь запросов — выходим
|
||||||
perror("mq_open req");
|
perror("mq_open req");
|
||||||
mq_close(qrep);
|
mq_close(qrep);
|
||||||
mq_unlink(replyq);
|
mq_unlink(replyq);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Инициализация отдельного генератора случайных чисел для этой пчелы
|
||||||
unsigned seed = (unsigned) (time(NULL) ^ (uintptr_t) me);
|
unsigned seed = (unsigned) (time(NULL) ^ (uintptr_t) me);
|
||||||
|
|
||||||
|
// Основной рабочий цикл пчелы
|
||||||
while (1) {
|
while (1) {
|
||||||
|
// Ждём случайное время 100–699 мс перед очередным запросом
|
||||||
int ms = 100 + (rand_r(&seed) % 600);
|
int ms = 100 + (rand_r(&seed) % 600);
|
||||||
msleep(ms);
|
msleep(ms);
|
||||||
|
|
||||||
|
// Формируем запрос к серверу
|
||||||
req_msg_t req;
|
req_msg_t req;
|
||||||
memset(&req, 0, sizeof(req));
|
memset(&req, 0, sizeof(req));
|
||||||
req.pid = me;
|
req.pid = me;
|
||||||
req.want = portion;
|
req.want = portion; // сколько мёда хотим получить
|
||||||
strncpy(req.replyq, replyq, sizeof(req.replyq) - 1);
|
strncpy(req.replyq, replyq, sizeof(req.replyq) - 1); // куда слать ответ
|
||||||
|
|
||||||
|
// Отправляем запрос в очередь REQ_QUEUE
|
||||||
if (mq_send(qreq, (const char *) &req, sizeof(req), 0) == -1) {
|
if (mq_send(qreq, (const char *) &req, sizeof(req), 0) == -1) {
|
||||||
perror("mq_send");
|
perror("mq_send");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ждём ответ от сервера в своей очереди
|
||||||
rep_msg_t rep;
|
rep_msg_t rep;
|
||||||
ssize_t rd = mq_receive(qrep, (char *) &rep, sizeof(rep), NULL);
|
ssize_t rd = mq_receive(qrep, (char *) &rep, sizeof(rep), NULL);
|
||||||
if (rd == -1) {
|
if (rd == -1) {
|
||||||
perror("mq_receive");
|
perror("mq_receive");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Если нам больше ничего не дают (granted <= 0) — выходим
|
||||||
if (rep.granted <= 0) {
|
if (rep.granted <= 0) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
dprintf(STDOUT_FILENO, "Bee %d got %d, remain %d\n", (int) me, rep.granted, rep.remain);
|
|
||||||
|
// Иначе логируем, сколько мёда получили и сколько осталось у сервера
|
||||||
|
dprintf(STDOUT_FILENO, "Bee %d got %d, remain %d\n",
|
||||||
|
(int) me, rep.granted, rep.remain);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Очистка ресурсов: закрываем очереди и удаляем личную очередь ответов
|
||||||
mq_close(qreq);
|
mq_close(qreq);
|
||||||
mq_close(qrep);
|
mq_close(qrep);
|
||||||
mq_unlink(replyq);
|
mq_unlink(replyq);
|
||||||
|
|||||||
Reference in New Issue
Block a user