Files
CS-LABS/lab_5/worker.c
2025-11-26 16:42:43 +07:00

99 lines
2.4 KiB
C

// worker.c
#define _GNU_SOURCE
#include <errno.h>
#include <mqueue.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "common.h"
static void msleep(int ms) {
struct timespec ts = {.tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L};
nanosleep(&ts, NULL);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <bee_portion>\n", argv[0]);
return 2;
}
int portion = atoi(argv[1]);
if (portion <= 0) {
fprintf(stderr, "portion must be >0\n");
return 2;
}
pid_t me = getpid();
char replyq[NAME_MAXLEN];
snprintf(replyq, sizeof(replyq), "/bee_%d", (int) me);
mq_unlink(replyq);
struct mq_attr attr;
memset(&attr, 0, sizeof(attr));
attr.mq_maxmsg = 10; // также укладываемся в лимит
attr.mq_msgsize = sizeof(rep_msg_t);
mqd_t qrep = mq_open(replyq, O_CREAT | O_RDONLY, 0666, &attr);
if (qrep == (mqd_t) -1) {
perror("mq_open reply");
return 1;
}
mqd_t qreq = (mqd_t) -1;
for (int i = 0; i < 50; i++) {
qreq = mq_open(REQ_QUEUE, O_WRONLY);
if (qreq != (mqd_t) -1) break;
if (errno != ENOENT) {
perror("mq_open req");
break;
}
msleep(100);
}
if (qreq == (mqd_t) -1) {
perror("mq_open req");
mq_close(qrep);
mq_unlink(replyq);
return 1;
}
unsigned seed = (unsigned) (time(NULL) ^ (uintptr_t) me);
while (1) {
int ms = 100 + (rand_r(&seed) % 600);
msleep(ms);
req_msg_t req;
memset(&req, 0, sizeof(req));
req.pid = me;
req.want = portion;
strncpy(req.replyq, replyq, sizeof(req.replyq) - 1);
if (mq_send(qreq, (const char *) &req, sizeof(req), 0) == -1) {
perror("mq_send");
break;
}
rep_msg_t rep;
ssize_t rd = mq_receive(qrep, (char *) &rep, sizeof(rep), NULL);
if (rd == -1) {
perror("mq_receive");
break;
}
if (rep.granted <= 0) {
break;
}
dprintf(STDOUT_FILENO, "Bee %d got %d, remain %d\n", (int) me, rep.granted, rep.remain);
}
mq_close(qreq);
mq_close(qrep);
mq_unlink(replyq);
return 0;
}