Compare commits
43 Commits
619953e6cc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| c016f13040 | |||
| a5fb7c6bb7 | |||
| e1aa4c2bac | |||
| 934edd83c8 | |||
| 8645cab6c5 | |||
| 5e0da4e0cb | |||
| 82dd7bf77f | |||
| 8a15b8d0f8 | |||
| 58f2fb3fe7 | |||
| eabaaf83f1 | |||
| 71dfd554f8 | |||
| 6cd4088087 | |||
| 139f41ae44 | |||
| ff6e412049 | |||
| f3a5c1f658 | |||
| cb9d0ac607 | |||
| 47cfeaddb4 | |||
| 84ff83b371 | |||
| baa8b5be9b | |||
| 47812b3900 | |||
| 69a2b7087c | |||
| afa6d4a7c2 | |||
| 1b46875e81 | |||
| 96015acb09 | |||
| c0b7b1b869 | |||
| 02c4d80b5e | |||
| 27b7c6c923 | |||
| 8bf5a27880 | |||
| 43b29e59e7 | |||
| eea51b9f9c | |||
| 3f44f11901 | |||
| 7975bfcdee | |||
| c508671675 | |||
| df9394869d | |||
| ca46482150 | |||
| 2b488e06eb | |||
| a1cf4b157d | |||
| 42bfff63e5 | |||
| a3090c6767 | |||
| 752615f96c | |||
| 86713716a9 | |||
| 331e89fbbe | |||
| f251380639 |
61
kirill/lab_5/Makefile
Normal file
61
kirill/lab_5/Makefile
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_MQ = -lrt # POSIX message queues on Linux
|
||||||
|
|
||||||
|
TEST_INPUT = test_input.txt
|
||||||
|
TEST_OUTPUT = test_output.txt
|
||||||
|
|
||||||
|
all: msg
|
||||||
|
|
||||||
|
# ===== POSIX MQ targets =====
|
||||||
|
msg: mq_server mq_client
|
||||||
|
|
||||||
|
mq_server: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
mq_client: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
# ===== Ручные тесты =====
|
||||||
|
|
||||||
|
test_server: msg
|
||||||
|
@echo "=== Запуск MQ сервера ==="
|
||||||
|
@echo "В другом терминале выполните: make test_client_manual"
|
||||||
|
./mq_server
|
||||||
|
|
||||||
|
test_client_manual: msg
|
||||||
|
@echo "=== Запуск MQ клиента (ручной тест) ==="
|
||||||
|
./mq_client $(TEST_INPUT) $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
# ===== Автотест: сервер в фоне + клиент =====
|
||||||
|
|
||||||
|
test_all: msg
|
||||||
|
@echo "=== Автотест MQ (server + client) ==="
|
||||||
|
@echo "Создание тестового входного файла..."
|
||||||
|
echo "aabbccddeeff" > $(TEST_INPUT)
|
||||||
|
@echo "Старт сервера в фоне..."
|
||||||
|
./mq_server & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
echo "Запуск клиента..."; \
|
||||||
|
./mq_client $(TEST_INPUT) $(TEST_OUTPUT); \
|
||||||
|
echo "Остановка сервера..."; \
|
||||||
|
kill $$SRV || true; \
|
||||||
|
wait $$SRV 2>/dev/null || true; \
|
||||||
|
echo "=== Содержимое $(TEST_OUTPUT) ==="; \
|
||||||
|
cat $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f mq_server mq_client *.o $(TEST_INPUT) $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " msg - Build POSIX MQ programs"
|
||||||
|
@echo " test_server - Run MQ server (headline only)"
|
||||||
|
@echo " test_client_manual- Run client (server must be running)"
|
||||||
|
@echo " test_all - Automatic end-to-end test (server+client)"
|
||||||
|
@echo " clean - Remove built and test files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all msg test_server test_client_manual test_all clean help
|
||||||
160
kirill/lab_5/client.c
Normal file
160
kirill/lab_5/client.c
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
// mq_client.c
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <errno.h>
|
||||||
|
|
||||||
|
#include <mqueue.h>
|
||||||
|
|
||||||
|
#define MQ_REQUEST "/mq_request"
|
||||||
|
#define MQ_RESPONSE "/mq_response"
|
||||||
|
#define MQ_MAXMSG 10
|
||||||
|
#define BUFFER_SIZE 4096
|
||||||
|
|
||||||
|
void print_usage(const char *progname) {
|
||||||
|
fprintf(stderr, "Usage: %s <input_file> <output_file>\n", progname);
|
||||||
|
fprintf(stderr, "Example: %s input.txt output.txt\n", progname);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc != 3) {
|
||||||
|
fprintf(stderr, "ERROR: Неверное количество аргументов\n");
|
||||||
|
print_usage(argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *input_file = argv[1];
|
||||||
|
const char *output_file = argv[2];
|
||||||
|
|
||||||
|
printf("=== MQ Client ===\n");
|
||||||
|
printf("Input file : %s\n", input_file);
|
||||||
|
printf("Output file: %s\n", output_file);
|
||||||
|
|
||||||
|
int in_fd = open(input_file, O_RDONLY);
|
||||||
|
if (in_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть входной файл %s: %s\n",
|
||||||
|
input_file, strerror(errno));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *buffer = malloc(BUFFER_SIZE);
|
||||||
|
if (!buffer) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось выделить память\n");
|
||||||
|
close(in_fd);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE - 1);
|
||||||
|
close(in_fd);
|
||||||
|
if (bytes_read < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось прочитать файл: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer[bytes_read] = '\0';
|
||||||
|
printf("Прочитано байт из файла: %zd\n", bytes_read);
|
||||||
|
|
||||||
|
struct mq_attr attr;
|
||||||
|
memset(&attr, 0, sizeof(attr));
|
||||||
|
attr.mq_flags = 0;
|
||||||
|
attr.mq_maxmsg = MQ_MAXMSG;
|
||||||
|
attr.mq_msgsize = BUFFER_SIZE;
|
||||||
|
attr.mq_curmsgs = 0;
|
||||||
|
|
||||||
|
mqd_t mq_req = mq_open(MQ_REQUEST, O_WRONLY);
|
||||||
|
if (mq_req == (mqd_t) -1) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Не удалось открыть очередь запросов %s: %s\n",
|
||||||
|
MQ_REQUEST, strerror(errno));
|
||||||
|
fprintf(stderr, "Убедитесь, что сервер запущен!\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mqd_t mq_resp = mq_open(MQ_RESPONSE, O_RDONLY);
|
||||||
|
if (mq_resp == (mqd_t) -1) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Не удалось открыть очередь ответов %s: %s\n",
|
||||||
|
MQ_RESPONSE, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mq_send(mq_req, buffer, (size_t) bytes_read, 0) == -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_send failed: %s\n", strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Отправлено байт: %zd\n", bytes_read);
|
||||||
|
|
||||||
|
// размер буфера >= mq_msgsize
|
||||||
|
ssize_t resp_bytes = mq_receive(mq_resp, buffer, BUFFER_SIZE, NULL);
|
||||||
|
if (resp_bytes < 0) {
|
||||||
|
fprintf(stderr, "ERROR: mq_receive failed: %s\n", strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resp_bytes >= BUFFER_SIZE)
|
||||||
|
resp_bytes = BUFFER_SIZE - 1;
|
||||||
|
buffer[resp_bytes] = '\0';
|
||||||
|
|
||||||
|
printf("Получено байт от сервера: %zd\n", resp_bytes);
|
||||||
|
|
||||||
|
char *repl_info = strstr(buffer, "\nREPLACEMENTS:");
|
||||||
|
long long replacements = 0;
|
||||||
|
|
||||||
|
if (repl_info) {
|
||||||
|
sscanf(repl_info, "\nREPLACEMENTS:%lld", &replacements);
|
||||||
|
*repl_info = '\0';
|
||||||
|
resp_bytes = repl_info - buffer;
|
||||||
|
} else {
|
||||||
|
fprintf(stderr,
|
||||||
|
"WARNING: Не найдена служебная строка REPLACEMENTS, "
|
||||||
|
"запишем весь ответ как есть\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
int out_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
|
S_IRUSR | S_IWUSR |
|
||||||
|
S_IRGRP | S_IWGRP |
|
||||||
|
S_IROTH | S_IWOTH);
|
||||||
|
if (out_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть выходной файл %s: %s\n",
|
||||||
|
output_file, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t written = write(out_fd, buffer, resp_bytes);
|
||||||
|
close(out_fd);
|
||||||
|
if (written != resp_bytes) {
|
||||||
|
fprintf(stderr, "ERROR: Ошибка записи в выходной файл\n");
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Записано байт в выходной файл: %zd\n", written);
|
||||||
|
printf("Количество выполненных замен: %lld\n", replacements);
|
||||||
|
printf("\nОбработка завершена успешно!\n");
|
||||||
|
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
157
kirill/lab_5/server.c
Normal file
157
kirill/lab_5/server.c
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
// mq_server.c
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <signal.h>
|
||||||
|
|
||||||
|
#include <mqueue.h> // POSIX message queues
|
||||||
|
|
||||||
|
#define MQ_REQUEST "/mq_request"
|
||||||
|
#define MQ_RESPONSE "/mq_response"
|
||||||
|
#define MQ_MAXMSG 10
|
||||||
|
#define BUFFER_SIZE 4096 // msgsize очереди и размер буферов
|
||||||
|
|
||||||
|
volatile sig_atomic_t running = 1;
|
||||||
|
|
||||||
|
void signal_handler(int sig) {
|
||||||
|
(void) sig;
|
||||||
|
running = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Заменить каждый третий символ на пробел
|
||||||
|
// (позиции 3, 6, 9, ... в исходном тексте)
|
||||||
|
long long process_text(const char *input, size_t len,
|
||||||
|
char *output, size_t out_size) {
|
||||||
|
if (out_size == 0) return -1;
|
||||||
|
|
||||||
|
long long replacements = 0;
|
||||||
|
size_t out_pos = 0;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < len && out_pos < out_size - 1; i++) {
|
||||||
|
char c = input[i];
|
||||||
|
|
||||||
|
// считаем позиции с 1
|
||||||
|
size_t pos = i + 1;
|
||||||
|
if (pos % 3 == 0) {
|
||||||
|
output[out_pos++] = ' ';
|
||||||
|
replacements++;
|
||||||
|
} else {
|
||||||
|
output[out_pos++] = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output[out_pos] = '\0';
|
||||||
|
return replacements;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
struct mq_attr attr;
|
||||||
|
mqd_t mq_req = (mqd_t) -1;
|
||||||
|
mqd_t mq_resp = (mqd_t) -1;
|
||||||
|
|
||||||
|
memset(&attr, 0, sizeof(attr));
|
||||||
|
attr.mq_flags = 0;
|
||||||
|
attr.mq_maxmsg = MQ_MAXMSG;
|
||||||
|
attr.mq_msgsize = BUFFER_SIZE;
|
||||||
|
attr.mq_curmsgs = 0;
|
||||||
|
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
mq_unlink(MQ_RESPONSE);
|
||||||
|
|
||||||
|
mq_req = mq_open(MQ_REQUEST, O_CREAT | O_RDONLY, 0666, &attr);
|
||||||
|
if (mq_req == (mqd_t) -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_open(%s) failed: %s\n",
|
||||||
|
MQ_REQUEST, strerror(errno));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mq_resp = mq_open(MQ_RESPONSE, O_CREAT | O_WRONLY, 0666, &attr);
|
||||||
|
if (mq_resp == (mqd_t) -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_open(%s) failed: %s\n",
|
||||||
|
MQ_RESPONSE, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("=== MQ Server started ===\n");
|
||||||
|
printf("Request queue : %s\n", MQ_REQUEST);
|
||||||
|
printf("Response queue: %s\n", MQ_RESPONSE);
|
||||||
|
|
||||||
|
signal(SIGINT, signal_handler);
|
||||||
|
signal(SIGTERM, signal_handler);
|
||||||
|
|
||||||
|
char in_buf[BUFFER_SIZE];
|
||||||
|
char out_buf[BUFFER_SIZE];
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
unsigned int prio = 0;
|
||||||
|
ssize_t bytes_read = mq_receive(mq_req, in_buf,
|
||||||
|
sizeof(in_buf), &prio);
|
||||||
|
if (bytes_read < 0) {
|
||||||
|
if (errno == EINTR && !running)
|
||||||
|
break;
|
||||||
|
if (errno == EINTR)
|
||||||
|
continue;
|
||||||
|
fprintf(stderr, "ERROR: mq_receive failed: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytes_read >= (ssize_t) sizeof(in_buf))
|
||||||
|
bytes_read = sizeof(in_buf) - 1;
|
||||||
|
in_buf[bytes_read] = '\0';
|
||||||
|
printf("Received request: %zd bytes\n", bytes_read);
|
||||||
|
|
||||||
|
long long repl = process_text(in_buf, (size_t) bytes_read,
|
||||||
|
out_buf, sizeof(out_buf));
|
||||||
|
if (repl < 0) {
|
||||||
|
const char *err_msg = "ERROR: processing failed\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Replacements done: %lld\n", repl);
|
||||||
|
|
||||||
|
char resp_buf[BUFFER_SIZE];
|
||||||
|
size_t processed_len = strlen(out_buf);
|
||||||
|
|
||||||
|
if (processed_len + 64 >= sizeof(resp_buf)) {
|
||||||
|
const char *err_msg = "ERROR: response too long\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(resp_buf, out_buf, processed_len);
|
||||||
|
int n = snprintf(resp_buf + processed_len,
|
||||||
|
sizeof(resp_buf) - processed_len,
|
||||||
|
"\nREPLACEMENTS:%lld\n", repl);
|
||||||
|
if (n < 0) {
|
||||||
|
const char *err_msg = "ERROR: snprintf failed\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t resp_len = processed_len + (size_t) n;
|
||||||
|
|
||||||
|
if (mq_send(mq_resp, resp_buf, resp_len, 0) == -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_send failed: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Response sent: %zu bytes\n\n", resp_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Server shutting down...\n");
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
mq_unlink(MQ_RESPONSE);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
51
kirill/lab_6/Makefile
Normal file
51
kirill/lab_6/Makefile
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_IPC = -lrt -pthread
|
||||||
|
|
||||||
|
SHM_NAME ?= /myshm
|
||||||
|
SEM_CLIENT_NAME ?= /sem_client
|
||||||
|
SEM_SERVER_NAME ?= /sem_server
|
||||||
|
SERVER_ITERS ?= 1000
|
||||||
|
|
||||||
|
all: shm
|
||||||
|
|
||||||
|
shm: server client
|
||||||
|
|
||||||
|
server: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
|
||||||
|
|
||||||
|
client: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
|
||||||
|
|
||||||
|
test_server: shm
|
||||||
|
@echo "=== Запуск сервера POSIX SHM+SEM ==="
|
||||||
|
@echo "В другом терминале выполните: make test_client"
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS)
|
||||||
|
|
||||||
|
test_client: shm
|
||||||
|
@echo "=== Запуск клиента, чтение input.txt, вывод на stdout ==="
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME)
|
||||||
|
|
||||||
|
test_all: shm
|
||||||
|
@echo "=== Автотест POSIX SHM+SEM с файлами input.txt/output.txt ==="
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS) & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME); \
|
||||||
|
wait $$SRV
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f server client
|
||||||
|
rm -f output.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " shm - Build POSIX SHM+SEM programs"
|
||||||
|
@echo " test_server - Run SHM+SEM server (client in another terminal)"
|
||||||
|
@echo " test_client - Run client reading input.txt"
|
||||||
|
@echo " test_all - Automatic end-to-end test with input.txt/output.txt"
|
||||||
|
@echo " clean - Remove built files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all shm test_server test_client test_all clean help
|
||||||
141
kirill/lab_6/client.c
Normal file
141
kirill/lab_6/client.c
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
// client.c
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/mman.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <semaphore.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#define SHM_BUFFER_SIZE 1024
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int has_data;
|
||||||
|
int result_code;
|
||||||
|
char buffer[SHM_BUFFER_SIZE];
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name>\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *shm_name = argv[1];
|
||||||
|
const char *sem_client_name = argv[2];
|
||||||
|
const char *sem_server_name = argv[3];
|
||||||
|
|
||||||
|
int shm_fd = shm_open(shm_name, O_RDWR, 0);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
shared_block_t *shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
close(shm_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_client = sem_open(sem_client_name, 0);
|
||||||
|
if (sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_server = sem_open(sem_server_name, 0);
|
||||||
|
if (sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
FILE *fin = fopen("input.txt", "r");
|
||||||
|
if (!fin) {
|
||||||
|
perror("fopen(input.txt)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char input[SHM_BUFFER_SIZE];
|
||||||
|
|
||||||
|
while (fgets(input, sizeof(input), fin) != NULL) {
|
||||||
|
size_t len = strlen(input);
|
||||||
|
if (len > 0 && input[len - 1] == '\n') {
|
||||||
|
input[len - 1] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
|
||||||
|
strncpy(shm_ptr->buffer, input, SHM_BUFFER_SIZE - 1);
|
||||||
|
shm_ptr->buffer[SHM_BUFFER_SIZE - 1] = '\0';
|
||||||
|
|
||||||
|
shm_ptr->has_data = 1;
|
||||||
|
|
||||||
|
if (sem_post(sem_client) == -1) {
|
||||||
|
perror("sem_post(sem_client)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_wait(sem_server) == -1) {
|
||||||
|
perror("sem_wait(sem_server)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shm_ptr->result_code != 0) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Server reported error, result_code = %d\n",
|
||||||
|
shm_ptr->result_code);
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%s\n", shm_ptr->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fin) == EOF) {
|
||||||
|
perror("fclose(input.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_close(sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_close(sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
6
kirill/lab_6/input.txt
Normal file
6
kirill/lab_6/input.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
abacaba
|
||||||
|
xxxxxx
|
||||||
|
hello
|
||||||
|
aaaaa
|
||||||
|
1abc1d1e1
|
||||||
|
qwerty
|
||||||
185
kirill/lab_6/server.c
Normal file
185
kirill/lab_6/server.c
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
// server.c
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/mman.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <semaphore.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#define SHM_BUFFER_SIZE 1024
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int has_data;
|
||||||
|
int result_code;
|
||||||
|
char buffer[SHM_BUFFER_SIZE];
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
static void process_line(char *s) {
|
||||||
|
if (!s) return;
|
||||||
|
for (size_t i = 0; s[i] != '\0'; ++i) {
|
||||||
|
if ((i + 1) % 3 == 0) {
|
||||||
|
s[i] = ' ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name> [iterations]\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *shm_name = argv[1];
|
||||||
|
const char *sem_client_name = argv[2];
|
||||||
|
const char *sem_server_name = argv[3];
|
||||||
|
|
||||||
|
int iterations = -1;
|
||||||
|
if (argc >= 5) {
|
||||||
|
char *endptr = NULL;
|
||||||
|
unsigned long tmp = strtoul(argv[4], &endptr, 10);
|
||||||
|
if (endptr == argv[4] || *endptr != '\0') {
|
||||||
|
fprintf(stderr, "Invalid iterations value: '%s'\n", argv[4]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
iterations = (int) tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
sem_unlink(sem_server_name);
|
||||||
|
|
||||||
|
int shm_fd = shm_open(shm_name,
|
||||||
|
O_CREAT | O_EXCL | O_RDWR,
|
||||||
|
S_IRUSR | S_IWUSR);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ftruncate(shm_fd, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("ftruncate");
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
shared_block_t *shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
shm_ptr->has_data = 0;
|
||||||
|
shm_ptr->result_code = 0;
|
||||||
|
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
|
||||||
|
|
||||||
|
sem_t *sem_client = sem_open(sem_client_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0);
|
||||||
|
if (sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_server = sem_open(sem_server_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0);
|
||||||
|
if (sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
FILE *fout = fopen("output.txt", "w");
|
||||||
|
if (!fout) {
|
||||||
|
perror("fopen(output.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
int processed_count = 0;
|
||||||
|
|
||||||
|
while (iterations < 0 || processed_count < iterations) {
|
||||||
|
if (sem_wait(sem_client) == -1) {
|
||||||
|
perror("sem_wait(sem_client)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shm_ptr->has_data) {
|
||||||
|
fprintf(stderr, "Warning: sem_client posted, but has_data == 0\n");
|
||||||
|
shm_ptr->result_code = -1;
|
||||||
|
} else {
|
||||||
|
process_line(shm_ptr->buffer);
|
||||||
|
shm_ptr->result_code = 0;
|
||||||
|
shm_ptr->has_data = 0;
|
||||||
|
processed_count++;
|
||||||
|
|
||||||
|
if (fout) {
|
||||||
|
fprintf(fout, "%s\n", shm_ptr->buffer);
|
||||||
|
fflush(fout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_post(sem_server) == -1) {
|
||||||
|
perror("sem_post(sem_server)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fout && fclose(fout) == EOF) {
|
||||||
|
perror("fclose(output.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (processed_count >= 0) {
|
||||||
|
printf("%d\n", processed_count);
|
||||||
|
} else {
|
||||||
|
printf("-1\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_close(sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_close(sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_unlink(sem_client_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_unlink(sem_server_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
if (shm_unlink(shm_name) == -1) {
|
||||||
|
perror("shm_unlink");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
43
kirill/lab_7/Makefile
Normal file
43
kirill/lab_7/Makefile
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c11 -g -pthread
|
||||||
|
|
||||||
|
MAX_REPL ?= 100
|
||||||
|
INPUT1 ?= in1.txt
|
||||||
|
OUTPUT1 ?= out1.txt
|
||||||
|
INPUT2 ?= in2.txt
|
||||||
|
OUTPUT2 ?= out2.txt
|
||||||
|
|
||||||
|
all: threads_third
|
||||||
|
|
||||||
|
threads_third: main.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
test_two: threads_third
|
||||||
|
@echo "=== Тест с двумя файлами ==="
|
||||||
|
@printf "abcdefghijk\n" > $(INPUT1)
|
||||||
|
@printf "xxxxxxxxxx\n" > $(INPUT2)
|
||||||
|
./threads_third $(MAX_REPL) $(INPUT1) $(OUTPUT1) $(INPUT2) $(OUTPUT2)
|
||||||
|
@echo "--- $(INPUT1) -> $(OUTPUT1) ---"
|
||||||
|
@cat $(INPUT1)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT1)
|
||||||
|
@echo
|
||||||
|
@echo "--- $(INPUT2) -> $(OUTPUT2) ---"
|
||||||
|
@cat $(INPUT2)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT2)
|
||||||
|
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f threads_third
|
||||||
|
rm -f in1.txt out1.txt in2.txt out2.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " all - build threads_third"
|
||||||
|
@echo " test_two - run two-file multithread test"
|
||||||
|
@echo " clean - remove binaries and test files"
|
||||||
|
@echo " help - show this help"
|
||||||
|
|
||||||
|
.PHONY: all test_one test_two test_all clean help
|
||||||
276
kirill/lab_7/main.c
Normal file
276
kirill/lab_7/main.c
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
// threads_third.c
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
|
||||||
|
#define RBUFSZ 4096
|
||||||
|
#define WBUFSZ 4096
|
||||||
|
#define MAX_THREADS 100
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char *input_path;
|
||||||
|
const char *output_path;
|
||||||
|
long long max_repl;
|
||||||
|
int thread_index;
|
||||||
|
int result;
|
||||||
|
} ThreadTask;
|
||||||
|
|
||||||
|
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||||
|
|
||||||
|
static void die_perror_thread(const char *what,
|
||||||
|
const char *path,
|
||||||
|
int exit_code) {
|
||||||
|
int saved = errno;
|
||||||
|
char msg[512];
|
||||||
|
|
||||||
|
if (path) {
|
||||||
|
snprintf(msg, sizeof(msg),
|
||||||
|
"%s: %s: %s\n", what, path, strerror(saved));
|
||||||
|
} else {
|
||||||
|
snprintf(msg, sizeof(msg),
|
||||||
|
"%s: %s\n", what, strerror(saved));
|
||||||
|
}
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
write(STDERR_FILENO, msg, strlen(msg));
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
(void) exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
static long long parse_ll(const char *s) {
|
||||||
|
char *end = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long long v = strtoll(s, &end, 10);
|
||||||
|
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||||
|
errno = EINVAL;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int process_file_third(const char *in_path,
|
||||||
|
const char *out_path,
|
||||||
|
long long cap) {
|
||||||
|
int in_fd = open(in_path, O_RDONLY);
|
||||||
|
if (in_fd < 0) {
|
||||||
|
die_perror_thread("open input failed", in_path, -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mode_t perms = S_IRUSR | S_IWUSR |
|
||||||
|
S_IRGRP | S_IWGRP |
|
||||||
|
S_IROTH | S_IWOTH;
|
||||||
|
|
||||||
|
int out_fd = open(out_path,
|
||||||
|
O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
|
perms);
|
||||||
|
if (out_fd < 0) {
|
||||||
|
die_perror_thread("open output failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char rbuf[RBUFSZ];
|
||||||
|
char wbuf[WBUFSZ];
|
||||||
|
size_t wlen = 0;
|
||||||
|
|
||||||
|
long long total_replacements = 0;
|
||||||
|
long long pos_in_file = 0;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
||||||
|
if (n > 0) {
|
||||||
|
for (ssize_t i = 0; i < n; i++, pos_in_file++) {
|
||||||
|
unsigned char c = (unsigned char) rbuf[i];
|
||||||
|
unsigned char outc = c;
|
||||||
|
|
||||||
|
if ((pos_in_file + 1) % 3 == 0 && total_replacements < cap) {
|
||||||
|
outc = ' ';
|
||||||
|
total_replacements++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wlen == sizeof(wbuf)) {
|
||||||
|
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||||
|
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||||
|
die_perror_thread("write failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
wlen = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
wbuf[wlen++] = (char) outc;
|
||||||
|
}
|
||||||
|
} else if (n == 0) {
|
||||||
|
if (wlen > 0) {
|
||||||
|
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||||
|
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||||
|
die_perror_thread("write failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
wlen = 0;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
die_perror_thread("read failed", in_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(in_fd) < 0) {
|
||||||
|
die_perror_thread("close input failed", in_path, -1);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(out_fd) < 0) {
|
||||||
|
die_perror_thread("close output failed", out_path, -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
char res[64];
|
||||||
|
int m = snprintf(res, sizeof(res), "%lld\n", total_replacements);
|
||||||
|
if (m > 0) {
|
||||||
|
write(STDOUT_FILENO, res, (size_t) m);
|
||||||
|
}
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *thread_func(void *arg) {
|
||||||
|
ThreadTask *task = (ThreadTask *) arg;
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
printf("[thread %d] start: %s -> %s, max_repl=%lld\n",
|
||||||
|
task->thread_index,
|
||||||
|
task->input_path,
|
||||||
|
task->output_path,
|
||||||
|
task->max_repl);
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
int rc = process_file_third(task->input_path,
|
||||||
|
task->output_path,
|
||||||
|
task->max_repl);
|
||||||
|
|
||||||
|
task->result = rc;
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
printf("[thread %d] finished with code %d\n",
|
||||||
|
task->thread_index,
|
||||||
|
task->result);
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void print_usage(const char *progname) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <max_replacements> <input1> <output1> [<input2> <output2> ...]\n",
|
||||||
|
progname);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 100 in1.txt out1.txt in2.txt out2.txt\n",
|
||||||
|
progname);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4 || ((argc - 2) % 2) != 0) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Недостаточное или неверное количество аргументов\n");
|
||||||
|
print_usage(argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
long long cap = parse_ll(argv[1]);
|
||||||
|
if (cap < 0) {
|
||||||
|
die_perror_thread("invalid max_replacements", argv[1], -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int num_files = (argc - 2) / 2;
|
||||||
|
if (num_files > MAX_THREADS) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Слишком много файлов (максимум %d пар)\n",
|
||||||
|
MAX_THREADS);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("=== Многопоточная обработка: каждый третий символ -> пробел ===\n");
|
||||||
|
printf("Главный поток TID: %lu\n", (unsigned long) pthread_self());
|
||||||
|
printf("Максимум замен на файл: %lld\n", cap);
|
||||||
|
printf("Количество файловых пар: %d\n\n", num_files);
|
||||||
|
|
||||||
|
pthread_t threads[MAX_THREADS];
|
||||||
|
ThreadTask tasks[MAX_THREADS];
|
||||||
|
|
||||||
|
for (int i = 0; i < num_files; i++) {
|
||||||
|
const char *input_path = argv[2 + i * 2];
|
||||||
|
const char *output_path = argv[3 + i * 2];
|
||||||
|
|
||||||
|
tasks[i].input_path = input_path;
|
||||||
|
tasks[i].output_path = output_path;
|
||||||
|
tasks[i].max_repl = cap;
|
||||||
|
tasks[i].thread_index = i + 1;
|
||||||
|
tasks[i].result = -1;
|
||||||
|
|
||||||
|
int rc = pthread_create(&threads[i],
|
||||||
|
NULL,
|
||||||
|
thread_func,
|
||||||
|
&tasks[i]);
|
||||||
|
if (rc != 0) {
|
||||||
|
errno = rc;
|
||||||
|
die_perror_thread("pthread_create failed", NULL, -1);
|
||||||
|
tasks[i].result = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int success_count = 0;
|
||||||
|
int error_count = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < num_files; i++) {
|
||||||
|
if (!threads[i]) {
|
||||||
|
error_count++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int rc = pthread_join(threads[i], NULL);
|
||||||
|
if (rc != 0) {
|
||||||
|
errno = rc;
|
||||||
|
die_perror_thread("pthread_join failed", NULL, -1);
|
||||||
|
error_count++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tasks[i].result == 0) {
|
||||||
|
success_count++;
|
||||||
|
} else {
|
||||||
|
error_count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\n=== Итоговая статистика ===\n");
|
||||||
|
printf("Всего потоков: %d\n", num_files);
|
||||||
|
printf("Успешно завершено: %d\n", success_count);
|
||||||
|
printf("С ошибкой: %d\n", error_count);
|
||||||
|
|
||||||
|
if (error_count > 0) {
|
||||||
|
printf("\nОБЩИЙ СТАТУС: Завершено с ошибками\n");
|
||||||
|
return -1;
|
||||||
|
} else {
|
||||||
|
printf("\nОБЩИЙ СТАТУС: Все потоки завершены успешно\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
50
kirill/lab_8/Makefile
Normal file
50
kirill/lab_8/Makefile
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c11 -g
|
||||||
|
|
||||||
|
all: server_udp_third client_udp_third
|
||||||
|
|
||||||
|
server_udp_third: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
client_udp_third: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
test_server: server_udp_third
|
||||||
|
@echo "=== Запуск UDP-сервера (каждый третий символ -> пробел) ==="
|
||||||
|
@echo "Выходной файл: out.txt"
|
||||||
|
./server_udp_third 5000 out.txt
|
||||||
|
|
||||||
|
test_client: client_udp_third
|
||||||
|
@echo "=== Запуск UDP-клиента ==="
|
||||||
|
@echo "Создаём input.txt"
|
||||||
|
@printf "abcdefghi\n1234567890\n" > input.txt
|
||||||
|
./client_udp_third 127.0.0.1 5000 input.txt
|
||||||
|
|
||||||
|
test_all: all
|
||||||
|
@echo "=== Автотест UDP (каждый третий символ -> пробел) ==="
|
||||||
|
@printf "abcdefghi\n1234567890\n" > input.txt
|
||||||
|
./server_udp_third 5000 out.txt & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
./client_udp_third 127.0.0.1 5000 input.txt; \
|
||||||
|
wait $$SRV; \
|
||||||
|
echo "--- input.txt ---"; \
|
||||||
|
cat input.txt; \
|
||||||
|
echo "--- out.txt ---"; \
|
||||||
|
cat out.txt
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f server_udp_third client_udp_third
|
||||||
|
rm -f input.txt out.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Targets:"
|
||||||
|
@echo " all - build server_udp_third and client_udp_third"
|
||||||
|
@echo " test_server - run server (port 5000, out.txt)"
|
||||||
|
@echo " test_client - run client to send input.txt"
|
||||||
|
@echo " test_all - end-to-end UDP test"
|
||||||
|
@echo " clean - remove binaries and test files"
|
||||||
|
@echo " help - show this help"
|
||||||
|
|
||||||
|
.PHONY: all test_server test_client test_all clean help
|
||||||
117
kirill/lab_8/client.c
Normal file
117
kirill/lab_8/client.c
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
// client_udp_third.c
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#define BUF_SIZE 4096
|
||||||
|
#define END_MARKER "END_OF_TRANSMISSION"
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <server_ip> <server_port> <input_file>\n",
|
||||||
|
argv[0]);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 127.0.0.1 5000 input.txt\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *server_ip = argv[1];
|
||||||
|
const char *server_port = argv[2];
|
||||||
|
const char *input_path = argv[3];
|
||||||
|
|
||||||
|
char *endptr = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long port_long = strtol(server_port, &endptr, 10);
|
||||||
|
if (errno != 0 || endptr == server_port || *endptr != '\0' ||
|
||||||
|
port_long <= 0 || port_long > 65535) {
|
||||||
|
fprintf(stderr, "ERROR: invalid port '%s'\n", server_port);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int port = (int) port_long;
|
||||||
|
|
||||||
|
FILE *fin = fopen(input_path, "r");
|
||||||
|
if (!fin) {
|
||||||
|
perror("fopen(input_file)");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (sockfd < 0) {
|
||||||
|
perror("socket");
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct sockaddr_in servaddr;
|
||||||
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
|
servaddr.sin_family = AF_INET;
|
||||||
|
servaddr.sin_port = htons(port);
|
||||||
|
|
||||||
|
if (inet_pton(AF_INET, server_ip, &servaddr.sin_addr) != 1) {
|
||||||
|
fprintf(stderr, "ERROR: invalid IP address '%s'\n", server_ip);
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char buf[BUF_SIZE];
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
size_t n = fread(buf, 1, sizeof(buf), fin);
|
||||||
|
if (n > 0) {
|
||||||
|
ssize_t sent = sendto(sockfd,
|
||||||
|
buf,
|
||||||
|
n,
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &servaddr,
|
||||||
|
sizeof(servaddr));
|
||||||
|
if (sent < 0 || (size_t) sent != n) {
|
||||||
|
perror("sendto");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (n < sizeof(buf)) {
|
||||||
|
if (ferror(fin)) {
|
||||||
|
perror("fread");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fin) == EOF) {
|
||||||
|
perror("fclose(input_file)");
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t sent = sendto(sockfd,
|
||||||
|
END_MARKER,
|
||||||
|
strlen(END_MARKER),
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &servaddr,
|
||||||
|
sizeof(servaddr));
|
||||||
|
if (sent < 0 || (size_t) sent != strlen(END_MARKER)) {
|
||||||
|
perror("sendto(END_MARKER)");
|
||||||
|
close(sockfd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("File '%s' sent to %s:%d, END marker transmitted.\n",
|
||||||
|
input_path, server_ip, port);
|
||||||
|
|
||||||
|
close(sockfd);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
142
kirill/lab_8/server.c
Normal file
142
kirill/lab_8/server.c
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
// server_udp_third.c
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#define BUF_SIZE 4096
|
||||||
|
#define END_MARKER "END_OF_TRANSMISSION"
|
||||||
|
|
||||||
|
static void process_block(char *buf,
|
||||||
|
ssize_t len,
|
||||||
|
long long *pos_counter,
|
||||||
|
long long *repl_counter) {
|
||||||
|
if (!buf || !pos_counter || !repl_counter) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ssize_t i = 0; i < len; i++) {
|
||||||
|
char c = buf[i];
|
||||||
|
long long pos = *pos_counter;
|
||||||
|
|
||||||
|
if (((pos + 1) % 3 == 0) && c != '\0') {
|
||||||
|
buf[i] = ' ';
|
||||||
|
(*repl_counter)++;
|
||||||
|
}
|
||||||
|
|
||||||
|
(*pos_counter)++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 3) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <port> <output_file>\n",
|
||||||
|
argv[0]);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 5000 out.txt\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *endptr = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long port_long = strtol(argv[1], &endptr, 10);
|
||||||
|
if (errno != 0 || endptr == argv[1] || *endptr != '\0' ||
|
||||||
|
port_long <= 0 || port_long > 65535) {
|
||||||
|
fprintf(stderr, "ERROR: invalid port '%s'\n", argv[1]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int port = (int) port_long;
|
||||||
|
|
||||||
|
const char *out_path = argv[2];
|
||||||
|
|
||||||
|
FILE *fout = fopen(out_path, "w");
|
||||||
|
if (!fout) {
|
||||||
|
perror("fopen(output_file)");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (sockfd < 0) {
|
||||||
|
perror("socket");
|
||||||
|
fclose(fout);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct sockaddr_in servaddr;
|
||||||
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
|
servaddr.sin_family = AF_INET;
|
||||||
|
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||||
|
servaddr.sin_port = htons(port);
|
||||||
|
|
||||||
|
if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
|
||||||
|
perror("bind");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fout);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("UDP server (third-char) listening on port %d, output file: %s\n",
|
||||||
|
port, out_path);
|
||||||
|
|
||||||
|
char buf[BUF_SIZE];
|
||||||
|
long long pos_counter = 0;
|
||||||
|
long long repl_counter = 0;
|
||||||
|
int done = 0;
|
||||||
|
|
||||||
|
while (!done) {
|
||||||
|
struct sockaddr_in cliaddr;
|
||||||
|
socklen_t cli_len = sizeof(cliaddr);
|
||||||
|
|
||||||
|
ssize_t n = recvfrom(sockfd,
|
||||||
|
buf,
|
||||||
|
sizeof(buf) - 1,
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &cliaddr,
|
||||||
|
&cli_len);
|
||||||
|
if (n < 0) {
|
||||||
|
perror("recvfrom");
|
||||||
|
repl_counter = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
buf[n] = '\0';
|
||||||
|
|
||||||
|
if (strcmp(buf, END_MARKER) == 0) {
|
||||||
|
printf("Received END marker from %s:%d, finishing.\n",
|
||||||
|
inet_ntoa(cliaddr.sin_addr),
|
||||||
|
ntohs(cliaddr.sin_port));
|
||||||
|
done = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
process_block(buf, n, &pos_counter, &repl_counter);
|
||||||
|
|
||||||
|
if (fwrite(buf, 1, (size_t) n, fout) != (size_t) n) {
|
||||||
|
perror("fwrite");
|
||||||
|
repl_counter = -1;
|
||||||
|
done = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fout) == EOF) {
|
||||||
|
perror("fclose(output_file)");
|
||||||
|
repl_counter = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
close(sockfd);
|
||||||
|
|
||||||
|
printf("Total replacements (every 3rd char): %lld\n", repl_counter);
|
||||||
|
if (repl_counter < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
#include <iostream>
|
|
||||||
#include <fstream>
|
|
||||||
#include <string>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <cerrno>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <climits>
|
|
||||||
|
|
||||||
static bool file_exists(const std::string &path) {
|
|
||||||
struct stat st{};
|
|
||||||
return ::stat(path.c_str(), &st) == 0; // stat success => exists [web:59]
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::string make_out_name(const std::string &in) {
|
|
||||||
std::size_t pos = in.find_last_of('.');
|
|
||||||
if (pos == std::string::npos) return in + ".out";
|
|
||||||
return in.substr(0, pos) + ".out";
|
|
||||||
}
|
|
||||||
|
|
||||||
static void print_usage(const char* prog) {
|
|
||||||
std::cerr << "Usage: " << prog << " <input_file> <replace_count>\n"; // positional args [web:59]
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool parse_ll(const char* s, long long& out) {
|
|
||||||
if (!s || !*s) return false;
|
|
||||||
errno = 0;
|
|
||||||
char* end = nullptr;
|
|
||||||
long long v = std::strtoll(s, &end, 10); // use endptr and errno [web:59]
|
|
||||||
if (errno == ERANGE) return false;
|
|
||||||
if (end == s || *end != '\0') return false;
|
|
||||||
out = v;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
|
||||||
if (argc != 3) {
|
|
||||||
print_usage(argv[0]);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string in_path = argv[1];
|
|
||||||
long long replace_limit = 0;
|
|
||||||
if (!parse_ll(argv[2], replace_limit) || replace_limit < 0) {
|
|
||||||
std::cerr << "Error: replace_count must be a non-negative integer.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!file_exists(in_path)) {
|
|
||||||
std::cerr << "Error: input file does not exist.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::ifstream in(in_path);
|
|
||||||
if (!in) {
|
|
||||||
std::cerr << "Error: cannot open input file.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string out_path = make_out_name(in_path);
|
|
||||||
std::ofstream out(out_path);
|
|
||||||
if (!out) {
|
|
||||||
std::cerr << "Error: cannot create output file.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
long long performed = 0;
|
|
||||||
std::string line;
|
|
||||||
|
|
||||||
while (performed < replace_limit && std::getline(in, line)) { // stop early when limit hit [web:59]
|
|
||||||
if (!line.empty()) {
|
|
||||||
char first = line.front();
|
|
||||||
for (char &c: line) {
|
|
||||||
if (c == first && c != ' ') {
|
|
||||||
c = ' ';
|
|
||||||
++performed;
|
|
||||||
if (performed >= replace_limit) break; // cap reached [web:44]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out << line;
|
|
||||||
if (!in.eof()) out << '\n';
|
|
||||||
if (!out) {
|
|
||||||
std::cerr << "Error: write error.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If limit reached mid-file, copy the rest unchanged
|
|
||||||
if (performed >= replace_limit) { // stream may be mid-line or between lines [web:59]
|
|
||||||
// Write remaining lines as-is
|
|
||||||
if (!in.eof()) {
|
|
||||||
// Flush any remaining part of current line already written; then dump rest
|
|
||||||
std::string rest;
|
|
||||||
while (std::getline(in, rest)) {
|
|
||||||
out << rest;
|
|
||||||
if (!in.eof()) out << '\n';
|
|
||||||
if (!out) {
|
|
||||||
std::cerr << "Error: write error.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::cout << performed << std::endl; // print actual replacements up to limit [web:59]
|
|
||||||
return 0; // success [web:59]
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
g++ -std=c++17 -O2 -Wall -Wextra 12_first_symbols_to_spaces.cpp -o 12_first_symbols_to_spaces
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
Здравствуйте, Андрей Васильевич!
|
|
||||||
|
|
||||||
TLDR:
|
|
||||||
ssh pajjilykk@cs.webmaple.ru
|
|
||||||
cd /home/pajjilykk/CS_LABS/lab_1
|
|
||||||
cat README.txt
|
|
||||||
|
|
||||||
Сообщаю, что лабораторная работа №1 по программированию выполнена и размещена на сервере. Данные для доступа и проверки:
|
|
||||||
|
|
||||||
Адрес сервера: cs.webmaple.ru
|
|
||||||
|
|
||||||
Логин: pajjilykk
|
|
||||||
|
|
||||||
Пароль: NSTU.CS
|
|
||||||
|
|
||||||
Путь к коду: /home/pajjilykk/CS_LABS/lab_1
|
|
||||||
|
|
||||||
Готов ответить на вопросы по коду и/или защите.
|
|
||||||
|
|
||||||
С уважением,
|
|
||||||
Куриленко Платон, группа АВТ-418
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
abcabcABC
|
|
||||||
Aaaaaa
|
|
||||||
1112233111
|
|
||||||
,,,,.,,
|
|
||||||
leading spaces here
|
|
||||||
tab leading here
|
|
||||||
first-letter f repeats: f fff f-f_f
|
|
||||||
ZzzZzZ
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
./12_first_symbols_to_spaces file.in 3
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
#include <unistd.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#define BUF_SIZE 1024
|
|
||||||
// пример программы обработки текстового файла средствами системых вызовов Linux
|
|
||||||
// учебник "Системное программирование в среде Linux", Гунько А.В., стр. 22
|
|
||||||
int main (int argc, char * argv [ ])
|
|
||||||
{
|
|
||||||
int inputFd, outputFd, openFlags;
|
|
||||||
mode_t filePerms ;
|
|
||||||
ssize_t numRead;
|
|
||||||
char buf[BUF_SIZE];
|
|
||||||
if (argc != 3)
|
|
||||||
{
|
|
||||||
printf("Usage: %s old-file new-file \n", argv[0]); exit(-1);
|
|
||||||
}
|
|
||||||
/* Открытие файлов ввода и вывода */
|
|
||||||
inputFd = open (argv[1], O_RDONLY);
|
|
||||||
if (inputFd == -1)
|
|
||||||
{
|
|
||||||
printf ("Error opening file %s\n", argv[1]) ; exit(-2);
|
|
||||||
}
|
|
||||||
openFlags = O_CREAT | O_WRONLY | O_TRUNC;
|
|
||||||
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* rw - rw - rw - */
|
|
||||||
outputFd = open (argv [2], openFlags, filePerms);
|
|
||||||
if (outputFd == -1)
|
|
||||||
{
|
|
||||||
printf ("Error opening file %s\n ", argv[2]) ; exit(-3);
|
|
||||||
}
|
|
||||||
/* Перемещение данных до достижения конца файла ввода или возникновения ошибки */
|
|
||||||
while ((numRead = read (inputFd, buf, BUF_SIZE)) > 0)
|
|
||||||
{
|
|
||||||
if (write (outputFd, buf, numRead) != numRead)
|
|
||||||
{
|
|
||||||
printf ("couldn't write whole buffer\n "); exit(-4);
|
|
||||||
}
|
|
||||||
if (numRead == -1)
|
|
||||||
{
|
|
||||||
printf ("read error\n "); exit(-5);
|
|
||||||
}
|
|
||||||
if (close (inputFd ) == -1 )
|
|
||||||
{
|
|
||||||
printf ("close input error\n"); exit(-6);
|
|
||||||
}
|
|
||||||
if (close (outputFd ) == -1 )
|
|
||||||
{
|
|
||||||
printf ("close output error\n"); exit(-7);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exit(EXIT_SUCCESS);
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
// пример программы обработки текстового файла средствами системых вызовов Linux
|
|
||||||
// учебник "Системное программирование в среде Linux", Гунько А.В.
|
|
||||||
int main(int argc, char *argv[]) {
|
|
||||||
int handle, numRead, total= 0;
|
|
||||||
char buf;
|
|
||||||
if (argc<2) {
|
|
||||||
printf("Usage: file textfile\n");
|
|
||||||
exit(-1);
|
|
||||||
}
|
|
||||||
// низкоуровневое открытие файла на чтение
|
|
||||||
handle = open( argv[1], O_RDONLY);
|
|
||||||
if (handle<0) {
|
|
||||||
printf("Error %d (%s) while open file: %s!\n",errno, strerror(errno),argv[1]);
|
|
||||||
exit(-2);
|
|
||||||
}
|
|
||||||
// цикл до конца файла
|
|
||||||
do {
|
|
||||||
// посимвольное чтение из файла
|
|
||||||
numRead = read( handle, &buf, 1);
|
|
||||||
if (buf == 0x20) total++; }
|
|
||||||
while (numRead > 0);
|
|
||||||
// Закрытие файла
|
|
||||||
close( handle);
|
|
||||||
printf("(PID: %d), File %s, spaces = %d\n", getpid(), argv[1], total);
|
|
||||||
// возвращаемое программой значение
|
|
||||||
return( total); }
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
Hi! This is a test.
|
|
||||||
Wait: are commas, periods, and exclamations replaced?
|
|
||||||
Let's check!
|
|
||||||
@#$%&*)_+
|
|
||||||
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
Hi9 This is a test9
|
|
||||||
Wait9 are commas9 periods9 and exclamations replaced9
|
|
||||||
Let's check9
|
|
||||||
@#$%&*)_+
|
|
||||||
|
|
||||||
|
|
||||||
Binary file not shown.
@@ -1,76 +0,0 @@
|
|||||||
#include <iostream>
|
|
||||||
#include <fstream>
|
|
||||||
#include <string>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
|
|
||||||
// ???????? ????????????? ?????
|
|
||||||
bool fileExists(const string& filename) {
|
|
||||||
struct stat buffer;
|
|
||||||
return (stat(filename.c_str(), &buffer) == 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ????????? ????? ????????? ????? ? ??????? ?????????? ?? ".out"
|
|
||||||
string getOutputFileName(const string& inputFileName) {
|
|
||||||
size_t pos = inputFileName.find_last_of('.');
|
|
||||||
if (pos == string::npos) {
|
|
||||||
// ???? ?????????? ???, ????????? .out
|
|
||||||
return inputFileName + ".out";
|
|
||||||
}
|
|
||||||
return inputFileName.substr(0, pos) + ".out"; // ???????? ??????????
|
|
||||||
}
|
|
||||||
|
|
||||||
// ????????, ???????? ?? ?????? ?????? ??????????, ?????????? ??????
|
|
||||||
bool isSign(char c) {
|
|
||||||
return (c == '!' || c == '?' || c == '.' || c == ',' || c == ';' || c == ':');
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
|
||||||
if (argc != 3) {
|
|
||||||
cerr << "Error: Missing arguments.\nUsage: " << argv[0] << " <inputfile> <symbol>\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
string inputFileName = argv[1];
|
|
||||||
char replacementSymbol = argv[2][0];
|
|
||||||
|
|
||||||
if (!fileExists(inputFileName)) {
|
|
||||||
cerr << "Error: Input file \"" << inputFileName << "\" does not exist.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
string outputFileName = getOutputFileName(inputFileName);
|
|
||||||
|
|
||||||
ifstream inFile(inputFileName);
|
|
||||||
if (!inFile) {
|
|
||||||
cerr << "Error: Cannot open input file.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
ofstream outFile(outputFileName);
|
|
||||||
if (!outFile) {
|
|
||||||
cerr << "Error: Cannot create output file.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int replaceCount = 0;
|
|
||||||
char ch;
|
|
||||||
while (inFile.get(ch)) {
|
|
||||||
if (isSign(ch)) {
|
|
||||||
ch = replacementSymbol;
|
|
||||||
replaceCount++;
|
|
||||||
}
|
|
||||||
outFile.put(ch);
|
|
||||||
if (!outFile) {
|
|
||||||
cerr << "Error: Write error occurred.\n";
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inFile.close();
|
|
||||||
outFile.close();
|
|
||||||
|
|
||||||
cout << replaceCount << endl; // ??????? ????? ?????
|
|
||||||
return replaceCount;
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
# Makefile
|
|
||||||
CC = gcc
|
|
||||||
CFLAGS = -Wall -Wextra -std=c99
|
|
||||||
LDFLAGS = -ldl
|
|
||||||
|
|
||||||
# Цель по умолчанию
|
|
||||||
all: task12 libtextlib.so
|
|
||||||
|
|
||||||
# Основная программа
|
|
||||||
task12: task12.c
|
|
||||||
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
|
|
||||||
|
|
||||||
# Динамическая библиотека
|
|
||||||
libtextlib.so: textlib.c
|
|
||||||
$(CC) $(CFLAGS) -fPIC -shared -o $@ $<
|
|
||||||
|
|
||||||
# Очистка
|
|
||||||
clean:
|
|
||||||
rm -f task12 libtextlib.so input.txt output.txt
|
|
||||||
|
|
||||||
# Тест
|
|
||||||
test: all
|
|
||||||
echo -e "Hello world\ntest line\nanother" > input.txt
|
|
||||||
./task12 input.txt output.txt 5 ./libtextlib.so
|
|
||||||
cat output.txt
|
|
||||||
|
|
||||||
.PHONY: all clean test
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
#include <unistd.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <dlfcn.h>
|
|
||||||
|
|
||||||
#define RBUFSZ 4096
|
|
||||||
#define WBUFSZ 4096
|
|
||||||
|
|
||||||
static void die_perror(const char *what, const char *path, int exit_code) {
|
|
||||||
int saved = errno;
|
|
||||||
char msg[512];
|
|
||||||
if (path) {
|
|
||||||
snprintf(msg, sizeof(msg), "%s: %s: %s\n", what, path, strerror(saved));
|
|
||||||
} else {
|
|
||||||
snprintf(msg, sizeof(msg), "%s: %s\n", what, strerror(saved));
|
|
||||||
}
|
|
||||||
(void) write(STDERR_FILENO, msg, strlen(msg));
|
|
||||||
_exit(exit_code);
|
|
||||||
}
|
|
||||||
|
|
||||||
static long long parse_ll(const char *s) {
|
|
||||||
char *end = NULL;
|
|
||||||
errno = 0;
|
|
||||||
long long v = strtoll(s, &end, 10);
|
|
||||||
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
|
||||||
errno = EINVAL;
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
|
||||||
if (argc != 5) {
|
|
||||||
const char *usage =
|
|
||||||
"Usage: lab2_var12 <input.txt> <output.txt> <max_replacements> <library.so>\n"
|
|
||||||
"Variant 12: Load text processing library dynamically and process file.\n"
|
|
||||||
"Library should provide 'process_text' function.\n";
|
|
||||||
(void) write(STDERR_FILENO, usage, strlen(usage));
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char *in_path = argv[1];
|
|
||||||
const char *out_path = argv[2];
|
|
||||||
long long cap = parse_ll(argv[3]);
|
|
||||||
const char *lib_path = argv[4];
|
|
||||||
|
|
||||||
if (cap < 0) {
|
|
||||||
die_perror("invalid max_replacements", argv[3], -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Динамически загружаем библиотеку
|
|
||||||
void *lib_handle = dlopen(lib_path, RTLD_LAZY);
|
|
||||||
if (!lib_handle) {
|
|
||||||
const char *error_msg = dlerror();
|
|
||||||
char msg[512];
|
|
||||||
snprintf(msg, sizeof(msg), "dlopen failed: %s\n", error_msg ? error_msg : "unknown error");
|
|
||||||
(void) write(STDERR_FILENO, msg, strlen(msg));
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Получаем указатель на функцию обработки текста
|
|
||||||
long long (*process_text)(const char*, const char*, long long) =
|
|
||||||
(long long (*)(const char*, const char*, long long)) dlsym(lib_handle, "process_text");
|
|
||||||
|
|
||||||
if (!process_text) {
|
|
||||||
const char *error_msg = dlerror();
|
|
||||||
char msg[512];
|
|
||||||
snprintf(msg, sizeof(msg), "dlsym failed: %s\n", error_msg ? error_msg : "unknown error");
|
|
||||||
(void) write(STDERR_FILENO, msg, strlen(msg));
|
|
||||||
dlclose(lib_handle);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Вызываем функцию из библиотеки
|
|
||||||
long long result = process_text(in_path, out_path, cap);
|
|
||||||
|
|
||||||
if (result < 0) {
|
|
||||||
die_perror("process_text failed", NULL, -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Закрываем библиотеку
|
|
||||||
dlclose(lib_handle);
|
|
||||||
|
|
||||||
// Выводим результат
|
|
||||||
char res[64];
|
|
||||||
int m = snprintf(res, sizeof(res), "%lld\n", result);
|
|
||||||
if (m > 0) {
|
|
||||||
(void) write(STDOUT_FILENO, res, (size_t) m);
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
#include <unistd.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
|
|
||||||
#define RBUFSZ 4096
|
|
||||||
#define WBUFSZ 4096
|
|
||||||
|
|
||||||
// Функция обработки текста
|
|
||||||
long long process_text(const char *in_path, const char *out_path, long long cap) {
|
|
||||||
int in_fd = open(in_path, O_RDONLY);
|
|
||||||
if (in_fd < 0) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
mode_t filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
|
|
||||||
int out_fd = open(out_path, O_CREAT | O_WRONLY | O_TRUNC, filePerms);
|
|
||||||
if (out_fd < 0) {
|
|
||||||
close(in_fd);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
char rbuf[RBUFSZ];
|
|
||||||
char wbuf[WBUFSZ];
|
|
||||||
size_t wlen = 0;
|
|
||||||
|
|
||||||
long long total_replacements = 0;
|
|
||||||
int at_line_start = 1;
|
|
||||||
unsigned char line_key = 0;
|
|
||||||
int replacing_enabled = 1;
|
|
||||||
|
|
||||||
for (;;) {
|
|
||||||
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
|
||||||
if (n > 0) {
|
|
||||||
for (ssize_t i = 0; i < n; i++) {
|
|
||||||
unsigned char c = (unsigned char) rbuf[i];
|
|
||||||
|
|
||||||
if (at_line_start) {
|
|
||||||
line_key = c;
|
|
||||||
at_line_start = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned char outc = c;
|
|
||||||
if (c == '\n') {
|
|
||||||
at_line_start = 1;
|
|
||||||
} else if (replacing_enabled && c == line_key) {
|
|
||||||
if (total_replacements < cap) {
|
|
||||||
outc = ' ';
|
|
||||||
total_replacements++;
|
|
||||||
if (total_replacements == cap) {
|
|
||||||
replacing_enabled = 0;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
replacing_enabled = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wlen == sizeof(wbuf)) {
|
|
||||||
ssize_t wrote = write(out_fd, wbuf, wlen);
|
|
||||||
if (wrote < 0 || (size_t) wrote != wlen) {
|
|
||||||
close(in_fd);
|
|
||||||
close(out_fd);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
wlen = 0;
|
|
||||||
}
|
|
||||||
wbuf[wlen++] = (char) outc;
|
|
||||||
}
|
|
||||||
} else if (n == 0) {
|
|
||||||
if (wlen > 0) {
|
|
||||||
ssize_t wrote = write(out_fd, wbuf, wlen);
|
|
||||||
if (wrote < 0 || (size_t) wrote != wlen) {
|
|
||||||
close(in_fd);
|
|
||||||
close(out_fd);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
wlen = 0;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
close(in_fd);
|
|
||||||
close(out_fd);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
close(in_fd);
|
|
||||||
close(out_fd);
|
|
||||||
|
|
||||||
return total_replacements;
|
|
||||||
}
|
|
||||||
Binary file not shown.
@@ -1,238 +0,0 @@
|
|||||||
# Лабораторная работа №4: Каналы передачи данных
|
|
||||||
|
|
||||||
## Цель работы
|
|
||||||
Получить навыки организации обмена информацией между процессами средствами неименованных или именованных каналов в программах на языке C в операционных системах семейства Linux.
|
|
||||||
|
|
||||||
## Описание задания
|
|
||||||
|
|
||||||
Лабораторная работа является модификацией лабораторной работы №3, в которой обмен данными между родительской и дочерними программами производится через программные каналы.
|
|
||||||
|
|
||||||
### Вариант 12
|
|
||||||
Программа читает текстовый файл построчно. Для каждой строки первый символ становится ключом, и все вхождения этого символа в строке заменяются пробелами, пока не будет достигнуто максимальное количество замен.
|
|
||||||
|
|
||||||
## Реализованные решения
|
|
||||||
|
|
||||||
### 1. Решение с неименованными каналами (pipes)
|
|
||||||
|
|
||||||
**Файлы:**
|
|
||||||
- `parent_pipe.c` - родительская программа
|
|
||||||
- `child_pipe.c` - дочерняя программа
|
|
||||||
|
|
||||||
**Принцип работы:**
|
|
||||||
1. Родительский процесс создает три канала для каждого дочернего процесса:
|
|
||||||
- `pipe_to_child` - для передачи данных дочернему процессу
|
|
||||||
- `pipe_from_child` - для получения обработанных данных
|
|
||||||
- `pipe_error` - для получения количества замен
|
|
||||||
|
|
||||||
2. Родительский процесс:
|
|
||||||
- Читает данные из входного файла
|
|
||||||
- Передает данные дочернему процессу через `pipe_to_child`
|
|
||||||
- Получает обработанные данные через `pipe_from_child`
|
|
||||||
- Записывает результат в выходной файл
|
|
||||||
|
|
||||||
3. Дочерний процесс:
|
|
||||||
- Перенаправляет stdin на чтение из канала (dup2)
|
|
||||||
- Перенаправляет stdout на запись в канал (dup2)
|
|
||||||
- Обрабатывает данные согласно варианту 12
|
|
||||||
- Возвращает количество замен через stderr
|
|
||||||
|
|
||||||
**Преимущества:**
|
|
||||||
- Простая реализация для родственных процессов
|
|
||||||
- Автоматическая синхронизация через блокирующие операции чтения/записи
|
|
||||||
- Нет необходимости в файловых дескрипторах на диске
|
|
||||||
|
|
||||||
**Недостатки:**
|
|
||||||
- Работает только между родственными процессами
|
|
||||||
- Ограниченный размер буфера канала
|
|
||||||
|
|
||||||
### 2. Решение с именованными каналами (FIFO)
|
|
||||||
|
|
||||||
**Файлы:**
|
|
||||||
- `fifo_server.c` - серверная программа
|
|
||||||
- `fifo_client.c` - клиентская программа
|
|
||||||
|
|
||||||
**Принцип работы:**
|
|
||||||
1. Сервер создает два именованных канала:
|
|
||||||
- `/tmp/fifo_request` - для получения запросов
|
|
||||||
- `/tmp/fifo_response` - для отправки ответов
|
|
||||||
|
|
||||||
2. Клиент:
|
|
||||||
- Читает данные из входного файла
|
|
||||||
- Отправляет данные серверу через `fifo_request`
|
|
||||||
- Получает обработанные данные через `fifo_response`
|
|
||||||
- Записывает результат в выходной файл
|
|
||||||
|
|
||||||
3. Сервер:
|
|
||||||
- Ожидает запросы от клиентов
|
|
||||||
- Обрабатывает данные согласно варианту 12
|
|
||||||
- Отправляет результат обратно клиенту
|
|
||||||
|
|
||||||
**Преимущества:**
|
|
||||||
- Работает между неродственными процессами
|
|
||||||
- Клиент-серверная архитектура
|
|
||||||
- Возможность обработки запросов от нескольких клиентов
|
|
||||||
|
|
||||||
**Недостатки:**
|
|
||||||
- Более сложная реализация
|
|
||||||
- Требуется управление файлами в файловой системе
|
|
||||||
- Необходима синхронизация между клиентом и сервером
|
|
||||||
|
|
||||||
## Компиляция и запуск
|
|
||||||
|
|
||||||
### Компиляция всех программ
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 all
|
|
||||||
```
|
|
||||||
|
|
||||||
### Тестирование с неименованными каналами
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_pipes
|
|
||||||
```
|
|
||||||
|
|
||||||
### Тестирование с именованными каналами
|
|
||||||
|
|
||||||
**Вариант 1: Автоматический тест**
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_fifo_auto
|
|
||||||
```
|
|
||||||
|
|
||||||
**Вариант 2: Ручной запуск в двух терминалах**
|
|
||||||
|
|
||||||
Терминал 1 (сервер):
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_fifo_server
|
|
||||||
```
|
|
||||||
|
|
||||||
Терминал 2 (клиент):
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_fifo_client
|
|
||||||
```
|
|
||||||
|
|
||||||
### Сравнение с оригинальной версией
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_compare
|
|
||||||
```
|
|
||||||
|
|
||||||
### Запуск всех тестов
|
|
||||||
```bash
|
|
||||||
make -f Makefile_lab4 test_all
|
|
||||||
```
|
|
||||||
|
|
||||||
## Примеры использования
|
|
||||||
|
|
||||||
### Неименованные каналы
|
|
||||||
```bash
|
|
||||||
./parent_pipe ./child_pipe 10 input1.txt output1.txt input2.txt output2.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### Именованные каналы
|
|
||||||
|
|
||||||
Запустить сервер:
|
|
||||||
```bash
|
|
||||||
./fifo_server 10
|
|
||||||
```
|
|
||||||
|
|
||||||
В другом терминале запустить клиент:
|
|
||||||
```bash
|
|
||||||
./fifo_client input1.txt output1.txt
|
|
||||||
./fifo_client input2.txt output2.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
## Обработка исключительных ситуаций
|
|
||||||
|
|
||||||
Программы предусматривают обработку следующих ошибок:
|
|
||||||
- Отсутствие или неверное количество входных параметров
|
|
||||||
- Ошибки открытия входного и/или выходного файла
|
|
||||||
- Ошибки создания каналов
|
|
||||||
- Ошибки создания дочерних процессов
|
|
||||||
- Ошибки чтения и записи через каналы
|
|
||||||
|
|
||||||
## Технические детали
|
|
||||||
|
|
||||||
### Используемые системные вызовы
|
|
||||||
|
|
||||||
**Неименованные каналы:**
|
|
||||||
- `pipe()` - создание канала
|
|
||||||
- `fork()` - создание дочернего процесса
|
|
||||||
- `dup2()` - дублирование файлового дескриптора
|
|
||||||
- `read()` / `write()` - чтение/запись данных
|
|
||||||
- `close()` - закрытие файлового дескриптора
|
|
||||||
- `waitpid()` - ожидание завершения дочернего процесса
|
|
||||||
- `execl()` - запуск новой программы
|
|
||||||
|
|
||||||
**Именованные каналы:**
|
|
||||||
- `mkfifo()` - создание именованного канала
|
|
||||||
- `open()` - открытие FIFO
|
|
||||||
- `read()` / `write()` - чтение/запись данных
|
|
||||||
- `close()` - закрытие FIFO
|
|
||||||
- `unlink()` - удаление FIFO
|
|
||||||
|
|
||||||
### Схема работы каналов
|
|
||||||
|
|
||||||
**Неименованные каналы (pipes):**
|
|
||||||
```
|
|
||||||
Родительский процесс Дочерний процесс
|
|
||||||
[файл] → read stdin ← pipe
|
|
||||||
↓ ↓
|
|
||||||
pipe → write read → process
|
|
||||||
↓
|
|
||||||
read ← pipe write → stdout
|
|
||||||
↓
|
|
||||||
write → [файл]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Именованные каналы (FIFO):**
|
|
||||||
```
|
|
||||||
Клиент Сервер
|
|
||||||
[файл] → read /tmp/fifo_request ← open
|
|
||||||
↓ ↓
|
|
||||||
write → /tmp/fifo_request read → process
|
|
||||||
↓
|
|
||||||
read ← /tmp/fifo_response write → /tmp/fifo_response
|
|
||||||
↓
|
|
||||||
write → [файл]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Структура проекта
|
|
||||||
|
|
||||||
```
|
|
||||||
lab4/
|
|
||||||
├── parent_pipe.c # Родительская программа (pipes)
|
|
||||||
├── child_pipe.c # Дочерняя программа (pipes)
|
|
||||||
├── fifo_server.c # Серверная программа (FIFO)
|
|
||||||
├── fifo_client.c # Клиентская программа (FIFO)
|
|
||||||
├── parent.c # Оригинальная версия (Lab 3)
|
|
||||||
├── lab1_var12.c # Оригинальная версия (Lab 1)
|
|
||||||
├── Makefile_lab4 # Makefile для компиляции и тестирования
|
|
||||||
└── README_lab4.md # Документация
|
|
||||||
```
|
|
||||||
|
|
||||||
## Контрольные вопросы (стр. 82)
|
|
||||||
|
|
||||||
1. **Что такое канал (pipe)?**
|
|
||||||
- Канал - это механизм межпроцессного взаимодействия (IPC), представляющий собой однонаправленный канал связи между процессами.
|
|
||||||
|
|
||||||
2. **В чем разница между именованными и неименованными каналами?**
|
|
||||||
- Неименованные каналы существуют только в памяти и доступны только родственным процессам
|
|
||||||
- Именованные каналы (FIFO) создаются в файловой системе и доступны любым процессам
|
|
||||||
|
|
||||||
3. **Как создать канал?**
|
|
||||||
- Неименованный: `int pipe(int fd[2])`
|
|
||||||
- Именованный: `int mkfifo(const char *pathname, mode_t mode)`
|
|
||||||
|
|
||||||
4. **Что происходит при чтении из пустого канала?**
|
|
||||||
- Процесс блокируется до тех пор, пока в канал не будут записаны данные
|
|
||||||
|
|
||||||
5. **Что происходит при записи в заполненный канал?**
|
|
||||||
- Процесс блокируется до тех пор, пока в канале не освободится место
|
|
||||||
|
|
||||||
6. **Как передать данные через канал?**
|
|
||||||
- Используя системные вызовы `write()` для записи и `read()` для чтения
|
|
||||||
|
|
||||||
7. **Зачем нужно закрывать неиспользуемые концы канала?**
|
|
||||||
- Для корректного определения EOF при чтении
|
|
||||||
- Для освобождения ресурсов
|
|
||||||
- Для предотвращения deadlock
|
|
||||||
|
|
||||||
## Автор
|
|
||||||
Лабораторная работа выполнена в рамках курса "Системное программирование в среде Linux"
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
// fifo_server.c - Серверная программа с использованием именованных каналов (FIFO)
|
|
||||||
// Вариант повышенной сложности для Lab 4
|
|
||||||
|
|
||||||
#include <stdio.h>
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <sys/types.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
#include <errno.h>
|
|
||||||
#include <signal.h>
|
|
||||||
|
|
||||||
#define FIFO_REQUEST "/tmp/fifo_request"
|
|
||||||
#define FIFO_RESPONSE "/tmp/fifo_response"
|
|
||||||
#define BUFFER_SIZE 4096
|
|
||||||
|
|
||||||
volatile sig_atomic_t running = 1;
|
|
||||||
|
|
||||||
void signal_handler(int sig) {
|
|
||||||
(void)sig;
|
|
||||||
running = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static long long parse_ll(const char *s) {
|
|
||||||
char *end = NULL;
|
|
||||||
errno = 0;
|
|
||||||
long long v = strtoll(s, &end, 10);
|
|
||||||
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
long long process_data(const char *input, size_t input_len, char *output,
|
|
||||||
size_t output_size, long long max_replacements) {
|
|
||||||
long long total_replacements = 0;
|
|
||||||
int at_line_start = 1;
|
|
||||||
unsigned char line_key = 0;
|
|
||||||
size_t out_pos = 0;
|
|
||||||
|
|
||||||
for (size_t i = 0; i < input_len && out_pos < output_size - 1; i++) {
|
|
||||||
unsigned char c = (unsigned char)input[i];
|
|
||||||
|
|
||||||
if (at_line_start) {
|
|
||||||
line_key = c;
|
|
||||||
at_line_start = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
unsigned char outc = c;
|
|
||||||
if (c == '\n') {
|
|
||||||
at_line_start = 1;
|
|
||||||
} else if (c == line_key && total_replacements < max_replacements) {
|
|
||||||
outc = ' ';
|
|
||||||
total_replacements++;
|
|
||||||
}
|
|
||||||
|
|
||||||
output[out_pos++] = (char)outc;
|
|
||||||
}
|
|
||||||
|
|
||||||
output[out_pos] = '\0';
|
|
||||||
return total_replacements;
|
|
||||||
}
|
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
|
||||||
if (argc != 2) {
|
|
||||||
fprintf(stderr, "Usage: %s <max_replacements>\n", argv[0]);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
long long max_replacements = parse_ll(argv[1]);
|
|
||||||
if (max_replacements < 0) {
|
|
||||||
fprintf(stderr, "ERROR: Invalid max_replacements\n");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
printf("=== FIFO Server запущен ===\n");
|
|
||||||
printf("Server PID: %d\n", getpid());
|
|
||||||
printf("Максимум замен: %lld\n", max_replacements);
|
|
||||||
|
|
||||||
// Устанавливаем обработчик сигналов
|
|
||||||
signal(SIGINT, signal_handler);
|
|
||||||
signal(SIGTERM, signal_handler);
|
|
||||||
|
|
||||||
// Удаляем старые FIFO, если существуют
|
|
||||||
unlink(FIFO_REQUEST);
|
|
||||||
unlink(FIFO_RESPONSE);
|
|
||||||
|
|
||||||
// Создаем именованные каналы
|
|
||||||
if (mkfifo(FIFO_REQUEST, 0666) == -1) {
|
|
||||||
perror("mkfifo request");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
if (mkfifo(FIFO_RESPONSE, 0666) == -1) {
|
|
||||||
perror("mkfifo response");
|
|
||||||
unlink(FIFO_REQUEST);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
printf("FIFO каналы созданы:\n");
|
|
||||||
printf(" Request: %s\n", FIFO_REQUEST);
|
|
||||||
printf(" Response: %s\n", FIFO_RESPONSE);
|
|
||||||
printf("Ожидание запросов от клиентов...\n\n");
|
|
||||||
|
|
||||||
while (running) {
|
|
||||||
// Открываем FIFO для чтения запроса
|
|
||||||
int fd_req = open(FIFO_REQUEST, O_RDONLY);
|
|
||||||
if (fd_req == -1) {
|
|
||||||
if (errno == EINTR) continue;
|
|
||||||
perror("open request FIFO");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Читаем данные от клиента
|
|
||||||
char *input_buffer = malloc(BUFFER_SIZE);
|
|
||||||
char *output_buffer = malloc(BUFFER_SIZE);
|
|
||||||
|
|
||||||
if (!input_buffer || !output_buffer) {
|
|
||||||
fprintf(stderr, "ERROR: Memory allocation failed\n");
|
|
||||||
close(fd_req);
|
|
||||||
free(input_buffer);
|
|
||||||
free(output_buffer);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
ssize_t bytes_read = read(fd_req, input_buffer, BUFFER_SIZE - 1);
|
|
||||||
close(fd_req);
|
|
||||||
|
|
||||||
if (bytes_read <= 0) {
|
|
||||||
free(input_buffer);
|
|
||||||
free(output_buffer);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
input_buffer[bytes_read] = '\0';
|
|
||||||
printf("Получен запрос: %zd байт\n", bytes_read);
|
|
||||||
|
|
||||||
// Обрабатываем данные
|
|
||||||
long long replacements = process_data(input_buffer, bytes_read,
|
|
||||||
output_buffer, BUFFER_SIZE,
|
|
||||||
max_replacements);
|
|
||||||
|
|
||||||
printf("Выполнено замен: %lld\n", replacements);
|
|
||||||
|
|
||||||
// Открываем FIFO для отправки ответа
|
|
||||||
int fd_resp = open(FIFO_RESPONSE, O_WRONLY);
|
|
||||||
if (fd_resp == -1) {
|
|
||||||
perror("open response FIFO");
|
|
||||||
free(input_buffer);
|
|
||||||
free(output_buffer);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Отправляем обработанные данные
|
|
||||||
size_t output_len = strlen(output_buffer);
|
|
||||||
ssize_t bytes_written = write(fd_resp, output_buffer, output_len);
|
|
||||||
|
|
||||||
// Отправляем количество замен (в отдельной строке)
|
|
||||||
char result[64];
|
|
||||||
snprintf(result, sizeof(result), "\nREPLACEMENTS:%lld\n", replacements);
|
|
||||||
write(fd_resp, result, strlen(result));
|
|
||||||
|
|
||||||
close(fd_resp);
|
|
||||||
|
|
||||||
printf("Отправлен ответ: %zd байт\n\n", bytes_written);
|
|
||||||
|
|
||||||
free(input_buffer);
|
|
||||||
free(output_buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Очистка
|
|
||||||
printf("\nЗавершение работы сервера...\n");
|
|
||||||
unlink(FIFO_REQUEST);
|
|
||||||
unlink(FIFO_RESPONSE);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
# Makefile for lab 4 - FIFO (named pipes) only
|
|
||||||
|
|
||||||
CC = gcc
|
|
||||||
CFLAGS = -Wall -Wextra -std=c99 -g
|
|
||||||
|
|
||||||
# Default target - build FIFO programs
|
|
||||||
all: fifo
|
|
||||||
|
|
||||||
# ===== FIFO targets =====
|
|
||||||
fifo: fifo_server fifo_client
|
|
||||||
|
|
||||||
fifo_server: fifo_server.c
|
|
||||||
$(CC) $(CFLAGS) -o $@ $<
|
|
||||||
|
|
||||||
fifo_client: fifo_client.c
|
|
||||||
$(CC) $(CFLAGS) -o $@ $<
|
|
||||||
|
|
||||||
# ===== Test files =====
|
|
||||||
test_files:
|
|
||||||
@echo "Создание тестовых файлов..."
|
|
||||||
echo "abbaabbaabbaabbaabbaabbaabbaabba" > input1.txt
|
|
||||||
echo "xyzxyzxyzxyzxyzxyzxyzxyz" >> input1.txt
|
|
||||||
echo "hello world hello" >> input1.txt
|
|
||||||
echo "testtest" > input2.txt
|
|
||||||
echo "aaaaaaa" >> input2.txt
|
|
||||||
echo "programming" > input3.txt
|
|
||||||
echo "ppppython" >> input3.txt
|
|
||||||
|
|
||||||
# ===== FIFO tests =====
|
|
||||||
test_fifo_server: fifo test_files
|
|
||||||
@echo "=== Запуск FIFO сервера ==="
|
|
||||||
@echo "В другом терминале выполните: make test_fifo_client"
|
|
||||||
./fifo_server 10
|
|
||||||
|
|
||||||
test_fifo_client: fifo test_files
|
|
||||||
@echo "=== Запуск FIFO клиента ===" & \
|
|
||||||
./fifo_client input1.txt output1_fifo.txt; \
|
|
||||||
./fifo_client input2.txt output2_fifo.txt; \
|
|
||||||
./fifo_client input3.txt output3_fifo.txt;
|
|
||||||
@echo "\n=== Результаты FIFO ==="
|
|
||||||
@echo "--- output1_fifo.txt ---"
|
|
||||||
@cat output1_fifo.txt || true
|
|
||||||
@echo "\n--- output2_fifo.txt ---"
|
|
||||||
@cat output2_fifo.txt || true
|
|
||||||
@echo "\n--- output3_fifo.txt ---"
|
|
||||||
@cat output3_fifo.txt || true
|
|
||||||
|
|
||||||
# Automatic FIFO test (server in background)
|
|
||||||
test_all: fifo test_files
|
|
||||||
@echo "=== Автоматический тест FIFO ==="
|
|
||||||
@./fifo_server 10 & \
|
|
||||||
SERVER_PID=$$!; \
|
|
||||||
sleep 1; \
|
|
||||||
./fifo_client input1.txt output1_fifo.txt; \
|
|
||||||
./fifo_client input2.txt output2_fifo.txt; \
|
|
||||||
./fifo_client input3.txt output3_fifo.txt; \
|
|
||||||
kill $$SERVER_PID 2>/dev/null || true; \
|
|
||||||
wait $$SERVER_PID 2>/dev/null || true
|
|
||||||
@echo "\n=== Результаты FIFO ==="
|
|
||||||
@echo "--- output1_fifo.txt ---"
|
|
||||||
@cat output1_fifo.txt || true
|
|
||||||
@echo "\n--- output2_fifo.txt ---"
|
|
||||||
@cat output2_fifo.txt || true
|
|
||||||
@echo "\n--- output3_fifo.txt ---"
|
|
||||||
@cat output3_fifo.txt || true
|
|
||||||
|
|
||||||
# Error handling test for FIFO
|
|
||||||
test_error: fifo
|
|
||||||
@echo "\n=== Тест обработки ошибки (несуществующий файл) - FIFO ==="
|
|
||||||
@./fifo_server 5 & \
|
|
||||||
SERVER_PID=$$!; \
|
|
||||||
sleep 1; \
|
|
||||||
./fifo_client nonexistent.txt output_error.txt || true; \
|
|
||||||
kill $$SERVER_PID 2>/dev/null || true; \
|
|
||||||
wait $$SERVER_PID 2>/dev/null || true
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
clean:
|
|
||||||
@echo "Очистка..."
|
|
||||||
rm -f fifo_server fifo_client
|
|
||||||
rm -f input1.txt input2.txt input3.txt
|
|
||||||
rm -f output*.txt
|
|
||||||
rm -f /tmp/fifo_request /tmp/fifo_response
|
|
||||||
|
|
||||||
# Help
|
|
||||||
help:
|
|
||||||
@echo "Доступные цели:"
|
|
||||||
@echo " all - Скомпилировать FIFO программы"
|
|
||||||
@echo " fifo - Скомпилировать fifo_server и fifo_client"
|
|
||||||
@echo " test_files - Создать тестовые входные файлы"
|
|
||||||
@echo " test_fifo_server - Запустить FIFO сервер (использовать с клиентом в другом терминале)"
|
|
||||||
@echo " test_fifo_client - Запустить FIFO клиент и показать результат"
|
|
||||||
@echo " test_fifo_auto - Автоматический тест FIFO (сервер в фоне)"
|
|
||||||
@echo " test_all - Запустить все тесты (FIFO)"
|
|
||||||
@echo " test_error_fifo - Тест обработки ошибок (несуществующий файл)"
|
|
||||||
@echo " clean - Удалить скомпилированные файлы и тесты"
|
|
||||||
|
|
||||||
.PHONY: all fifo test_files test_fifo_server test_fifo_client test_all \
|
|
||||||
test_error clean help
|
|
||||||
@@ -1,399 +0,0 @@
|
|||||||
# Инструкция по запуску Лабораторной работы №4
|
|
||||||
|
|
||||||
## Быстрый старт
|
|
||||||
|
|
||||||
### 1. Подготовка файлов
|
|
||||||
|
|
||||||
Создайте рабочую директорию и поместите в неё следующие файлы:
|
|
||||||
- `parent_pipe.c` - родительская программа (pipes)
|
|
||||||
- `child_pipe.c` - дочерняя программа (pipes)
|
|
||||||
- `fifo_server.c` - серверная программа (FIFO)
|
|
||||||
- `fifo_client.c` - клиентская программа (FIFO)
|
|
||||||
- `Makefile_lab4` - Makefile для компиляции
|
|
||||||
- Оригинальные файлы: `parent.c`, `lab1_var12.c`, `Makefile` (для сравнения)
|
|
||||||
|
|
||||||
### 2. Компиляция
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Компилировать все программы
|
|
||||||
make -f Makefile_lab4 all
|
|
||||||
|
|
||||||
# Или компилировать отдельно:
|
|
||||||
make -f Makefile_lab4 pipes # Только pipes
|
|
||||||
make -f Makefile_lab4 fifo # Только FIFO
|
|
||||||
make -f Makefile_lab4 original # Оригинальная версия
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Автоматическое тестирование
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Тест с неименованными каналами (pipes)
|
|
||||||
make -f Makefile_lab4 test_pipes
|
|
||||||
|
|
||||||
# Автоматический тест с именованными каналами (FIFO)
|
|
||||||
make -f Makefile_lab4 test_fifo_auto
|
|
||||||
|
|
||||||
# Сравнение с оригинальной версией
|
|
||||||
make -f Makefile_lab4 test_compare
|
|
||||||
|
|
||||||
# Запустить все тесты
|
|
||||||
make -f Makefile_lab4 test_all
|
|
||||||
```
|
|
||||||
|
|
||||||
## Подробные инструкции
|
|
||||||
|
|
||||||
### Вариант 1: Неименованные каналы (Pipes)
|
|
||||||
|
|
||||||
#### Компиляция
|
|
||||||
```bash
|
|
||||||
gcc -Wall -Wextra -std=c99 -g -o parent_pipe parent_pipe.c
|
|
||||||
gcc -Wall -Wextra -std=c99 -g -o child_pipe child_pipe.c
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Создание тестовых файлов
|
|
||||||
```bash
|
|
||||||
echo "abbaabbaabbaabbaabbaabbaabbaabba" > input1.txt
|
|
||||||
echo "xyzxyzxyzxyzxyzxyzxyzxyz" >> input1.txt
|
|
||||||
echo "hello world hello" >> input1.txt
|
|
||||||
|
|
||||||
echo "testtest" > input2.txt
|
|
||||||
echo "aaaaaaa" >> input2.txt
|
|
||||||
|
|
||||||
echo "programming" > input3.txt
|
|
||||||
echo "ppppython" >> input3.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Запуск
|
|
||||||
```bash
|
|
||||||
# Формат: ./parent_pipe <child_program> <max_replacements> <in1> <out1> [<in2> <out2> ...]
|
|
||||||
|
|
||||||
# Обработка одного файла
|
|
||||||
./parent_pipe ./child_pipe 10 input1.txt output1.txt
|
|
||||||
|
|
||||||
# Обработка нескольких файлов параллельно
|
|
||||||
./parent_pipe ./child_pipe 10 input1.txt output1.txt input2.txt output2.txt input3.txt output3.txt
|
|
||||||
|
|
||||||
# Разные лимиты замен
|
|
||||||
./parent_pipe ./child_pipe 5 input1.txt output1_5.txt
|
|
||||||
./parent_pipe ./child_pipe 20 input1.txt output1_20.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Просмотр результатов
|
|
||||||
```bash
|
|
||||||
cat output1.txt
|
|
||||||
cat output2.txt
|
|
||||||
cat output3.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### Вариант 2: Именованные каналы (FIFO)
|
|
||||||
|
|
||||||
#### Компиляция
|
|
||||||
```bash
|
|
||||||
gcc -Wall -Wextra -std=c99 -g -o fifo_server fifo_server.c
|
|
||||||
gcc -Wall -Wextra -std=c99 -g -o fifo_client fifo_client.c
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Вариант 2.1: Запуск в двух терминалах
|
|
||||||
|
|
||||||
**Терминал 1 (Сервер):**
|
|
||||||
```bash
|
|
||||||
./fifo_server 10
|
|
||||||
```
|
|
||||||
Сервер запустится и будет ожидать подключения клиентов.
|
|
||||||
|
|
||||||
**Терминал 2 (Клиент):**
|
|
||||||
```bash
|
|
||||||
# Формат: ./fifo_client <input_file> <output_file>
|
|
||||||
|
|
||||||
./fifo_client input1.txt output1_fifo.txt
|
|
||||||
./fifo_client input2.txt output2_fifo.txt
|
|
||||||
./fifo_client input3.txt output3_fifo.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
После обработки всех файлов остановите сервер: Ctrl+C в терминале 1.
|
|
||||||
|
|
||||||
#### Вариант 2.2: Автоматический запуск (одна команда)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Сервер запустится в фоне, обработает запросы и автоматически остановится
|
|
||||||
make -f Makefile_lab4 test_fifo_auto
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Вариант 2.3: Ручной запуск в фоне
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Запустить сервер в фоне
|
|
||||||
./fifo_server 10 &
|
|
||||||
SERVER_PID=$!
|
|
||||||
|
|
||||||
# Подождать запуска сервера
|
|
||||||
sleep 1
|
|
||||||
|
|
||||||
# Отправить запросы
|
|
||||||
./fifo_client input1.txt output1_fifo.txt
|
|
||||||
./fifo_client input2.txt output2_fifo.txt
|
|
||||||
./fifo_client input3.txt output3_fifo.txt
|
|
||||||
|
|
||||||
# Остановить сервер
|
|
||||||
kill $SERVER_PID
|
|
||||||
```
|
|
||||||
|
|
||||||
## Тестирование обработки ошибок
|
|
||||||
|
|
||||||
### Несуществующий входной файл
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Pipes
|
|
||||||
./parent_pipe ./child_pipe 5 nonexistent.txt output.txt
|
|
||||||
|
|
||||||
# FIFO
|
|
||||||
./fifo_server 5 &
|
|
||||||
sleep 1
|
|
||||||
./fifo_client nonexistent.txt output.txt
|
|
||||||
killall fifo_server
|
|
||||||
```
|
|
||||||
|
|
||||||
### Неверное количество аргументов
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Недостаточно аргументов
|
|
||||||
./parent_pipe ./child_pipe 5
|
|
||||||
|
|
||||||
# Нечетное количество файлов
|
|
||||||
./parent_pipe ./child_pipe 5 input1.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### Клиент без сервера (FIFO)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Попытка подключиться при выключенном сервере
|
|
||||||
./fifo_client input1.txt output1.txt
|
|
||||||
# Ожидается: "ERROR: Не удалось открыть FIFO запроса"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Сравнение результатов
|
|
||||||
|
|
||||||
### Сравнение pipes vs original
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Запустить обе версии
|
|
||||||
./parent_pipe ./child_pipe 10 input1.txt output1_pipe.txt
|
|
||||||
./parent ./lab1_var12 10 input1.txt output1_orig.txt
|
|
||||||
|
|
||||||
# Сравнить результаты
|
|
||||||
diff output1_pipe.txt output1_orig.txt
|
|
||||||
|
|
||||||
# Если различий нет - программа работает корректно
|
|
||||||
```
|
|
||||||
|
|
||||||
### Сравнение FIFO vs pipes
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Pipes
|
|
||||||
./parent_pipe ./child_pipe 10 input1.txt output1_pipe.txt
|
|
||||||
|
|
||||||
# FIFO
|
|
||||||
./fifo_server 10 &
|
|
||||||
sleep 1
|
|
||||||
./fifo_client input1.txt output1_fifo.txt
|
|
||||||
killall fifo_server
|
|
||||||
|
|
||||||
# Сравнение
|
|
||||||
diff output1_pipe.txt output1_fifo.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
## Анализ работы программ
|
|
||||||
|
|
||||||
### Просмотр процессов
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Во время работы parent_pipe в другом терминале:
|
|
||||||
ps aux | grep child_pipe
|
|
||||||
ps aux | grep parent_pipe
|
|
||||||
|
|
||||||
# Просмотр открытых файловых дескрипторов
|
|
||||||
lsof -c parent_pipe
|
|
||||||
lsof -c child_pipe
|
|
||||||
```
|
|
||||||
|
|
||||||
### Просмотр FIFO файлов
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Во время работы сервера:
|
|
||||||
ls -la /tmp/fifo_*
|
|
||||||
|
|
||||||
# Информация о типе файла
|
|
||||||
file /tmp/fifo_request
|
|
||||||
file /tmp/fifo_response
|
|
||||||
```
|
|
||||||
|
|
||||||
### Трассировка системных вызовов
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Трассировка работы с каналами
|
|
||||||
strace -e trace=pipe,read,write,fork,execl ./parent_pipe ./child_pipe 10 input1.txt output1.txt
|
|
||||||
|
|
||||||
# Трассировка FIFO операций
|
|
||||||
strace -e trace=open,read,write,mkfifo ./fifo_server 10
|
|
||||||
```
|
|
||||||
|
|
||||||
## Очистка
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Удалить скомпилированные программы и тестовые файлы
|
|
||||||
make -f Makefile_lab4 clean
|
|
||||||
|
|
||||||
# Или вручную:
|
|
||||||
rm -f parent_pipe child_pipe fifo_server fifo_client
|
|
||||||
rm -f parent lab1_var12
|
|
||||||
rm -f input*.txt output*.txt
|
|
||||||
rm -f /tmp/fifo_request /tmp/fifo_response
|
|
||||||
```
|
|
||||||
|
|
||||||
## Типичные проблемы и решения
|
|
||||||
|
|
||||||
### Проблема 1: "Permission denied" при запуске
|
|
||||||
|
|
||||||
**Решение:**
|
|
||||||
```bash
|
|
||||||
chmod +x parent_pipe child_pipe fifo_server fifo_client
|
|
||||||
```
|
|
||||||
|
|
||||||
### Проблема 2: FIFO клиент зависает
|
|
||||||
|
|
||||||
**Причина:** Сервер не запущен.
|
|
||||||
|
|
||||||
**Решение:** Убедитесь, что сервер запущен:
|
|
||||||
```bash
|
|
||||||
ps aux | grep fifo_server
|
|
||||||
```
|
|
||||||
|
|
||||||
### Проблема 3: "Address already in use" для FIFO
|
|
||||||
|
|
||||||
**Причина:** FIFO файлы остались после некорректного завершения.
|
|
||||||
|
|
||||||
**Решение:**
|
|
||||||
```bash
|
|
||||||
rm -f /tmp/fifo_request /tmp/fifo_response
|
|
||||||
```
|
|
||||||
|
|
||||||
### Проблема 4: Зомби-процессы
|
|
||||||
|
|
||||||
**Причина:** Родительский процесс не вызвал wait() для дочерних.
|
|
||||||
|
|
||||||
**Решение:** В коде уже реализован waitpid(), но если проблема возникла:
|
|
||||||
```bash
|
|
||||||
# Просмотр зомби
|
|
||||||
ps aux | grep defunct
|
|
||||||
|
|
||||||
# Завершить родительский процесс
|
|
||||||
killall parent_pipe
|
|
||||||
```
|
|
||||||
|
|
||||||
### Проблема 5: Broken pipe
|
|
||||||
|
|
||||||
**Причина:** Попытка записи в канал, у которого закрыт конец для чтения.
|
|
||||||
|
|
||||||
**Решение:** Убедитесь, что оба конца канала правильно настроены и дочерний процесс не завершился преждевременно.
|
|
||||||
|
|
||||||
## Дополнительные команды
|
|
||||||
|
|
||||||
### Справка по использованию
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Показать все доступные команды Makefile
|
|
||||||
make -f Makefile_lab4 help
|
|
||||||
```
|
|
||||||
|
|
||||||
### Компиляция с отладочной информацией
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Уже включено флагом -g, запуск с gdb:
|
|
||||||
gdb ./parent_pipe
|
|
||||||
(gdb) run ./child_pipe 10 input1.txt output1.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### Проверка утечек памяти
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Для pipes
|
|
||||||
valgrind --leak-check=full ./parent_pipe ./child_pipe 10 input1.txt output1.txt
|
|
||||||
|
|
||||||
# Для FIFO сервера
|
|
||||||
valgrind --leak-check=full ./fifo_server 10
|
|
||||||
```
|
|
||||||
|
|
||||||
## Примеры вывода
|
|
||||||
|
|
||||||
### Успешное выполнение pipes
|
|
||||||
|
|
||||||
```
|
|
||||||
=== Запуск родительского процесса с каналами ===
|
|
||||||
Родительский PID: 12345
|
|
||||||
Программа для запуска: ./child_pipe
|
|
||||||
Максимум замен: 10
|
|
||||||
Количество файловых пар: 2
|
|
||||||
|
|
||||||
Создание процесса 1 для файлов: input1.txt -> output1.txt
|
|
||||||
Создание процесса 2 для файлов: input2.txt -> output2.txt
|
|
||||||
|
|
||||||
=== Обработка файлов через каналы ===
|
|
||||||
|
|
||||||
Обработка процесса PID=12346 (input1.txt -> output1.txt)
|
|
||||||
Отправлено байт: 87
|
|
||||||
Получено байт: 87
|
|
||||||
Количество замен: 10
|
|
||||||
Статус: SUCCESS
|
|
||||||
|
|
||||||
Обработка процесса PID=12347 (input2.txt -> output2.txt)
|
|
||||||
Отправлено байт: 17
|
|
||||||
Получено байт: 17
|
|
||||||
Количество замен: 6
|
|
||||||
Статус: SUCCESS
|
|
||||||
|
|
||||||
=== Итоговая статистика ===
|
|
||||||
Всего запущено процессов: 2
|
|
||||||
Успешно завершено: 2
|
|
||||||
Завершено с ошибкой: 0
|
|
||||||
|
|
||||||
ОБЩИЙ СТАТУС: Все процессы завершены успешно
|
|
||||||
```
|
|
||||||
|
|
||||||
### Успешное выполнение FIFO
|
|
||||||
|
|
||||||
```
|
|
||||||
=== FIFO Server запущен ===
|
|
||||||
Server PID: 12350
|
|
||||||
Максимум замен: 10
|
|
||||||
FIFO каналы созданы:
|
|
||||||
Request: /tmp/fifo_request
|
|
||||||
Response: /tmp/fifo_response
|
|
||||||
Ожидание запросов от клиентов...
|
|
||||||
|
|
||||||
Получен запрос: 87 байт
|
|
||||||
Выполнено замен: 10
|
|
||||||
Отправлен ответ: 87 байт
|
|
||||||
```
|
|
||||||
|
|
||||||
```
|
|
||||||
=== FIFO Client ===
|
|
||||||
Client PID: 12351
|
|
||||||
Входной файл: input1.txt
|
|
||||||
Выходной файл: output1.txt
|
|
||||||
Прочитано байт из файла: 87
|
|
||||||
Отправка запроса серверу...
|
|
||||||
Отправлено байт: 87
|
|
||||||
Ожидание ответа от сервера...
|
|
||||||
Получено байт от сервера: 100
|
|
||||||
Записано байт в выходной файл: 87
|
|
||||||
Количество выполненных замен: 10
|
|
||||||
|
|
||||||
Обработка завершена успешно!
|
|
||||||
```
|
|
||||||
|
|
||||||
## Контакты и поддержка
|
|
||||||
|
|
||||||
При возникновении вопросов обратитесь к:
|
|
||||||
- Отчету лабораторной работы (PDF)
|
|
||||||
- Комментариям в исходном коде
|
|
||||||
- Документации Linux man pages: `man pipe`, `man mkfifo`, `man fork`, `man dup2`
|
|
||||||
65
mine/lab_4/Makefile
Normal file
65
mine/lab_4/Makefile
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
|
||||||
|
# Default target - build FIFO programs
|
||||||
|
all: fifo
|
||||||
|
|
||||||
|
# ===== FIFO targets =====
|
||||||
|
fifo: fifo_server fifo_client
|
||||||
|
|
||||||
|
fifo_server: fifo_server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
fifo_client: fifo_client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
# ===== Test files =====
|
||||||
|
files:
|
||||||
|
@echo "Создание тестовых файлов..."
|
||||||
|
echo "abbaabbaabbaabbaabbaabbaabbaabba" > input1.txt
|
||||||
|
echo "xyzxyzxyzxyzxyzxyzxyzxyz" >> input1.txt
|
||||||
|
echo "hello world hello" >> input1.txt
|
||||||
|
echo "testtest" > input2.txt
|
||||||
|
echo "aaaaaaa" >> input2.txt
|
||||||
|
echo "programming" > input3.txt
|
||||||
|
echo "ppppython" >> input3.txt
|
||||||
|
|
||||||
|
# ===== FIFO tests =====
|
||||||
|
test_server: fifo files
|
||||||
|
@echo "=== Запуск FIFO сервера ==="
|
||||||
|
@echo "В другом терминале выполните: make test_fifo_client"
|
||||||
|
@echo "\n\n"
|
||||||
|
./fifo_server 10
|
||||||
|
|
||||||
|
test_client: fifo files
|
||||||
|
@echo "=== Запуск FIFO клиента ===\n\n" & \
|
||||||
|
./fifo_client input1.txt output1_fifo.txt; \
|
||||||
|
./fifo_client input2.txt output2_fifo.txt; \
|
||||||
|
./fifo_client input3.txt output3_fifo.txt;
|
||||||
|
@echo "\n=== Результаты FIFO ===\n"
|
||||||
|
@echo "--- output1_fifo.txt ---"
|
||||||
|
@cat output1_fifo.txt || true
|
||||||
|
@echo "\n--- output2_fifo.txt ---"
|
||||||
|
@cat output2_fifo.txt || true
|
||||||
|
@echo "\n--- output3_fifo.txt ---"
|
||||||
|
@cat output3_fifo.txt || true
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f fifo_server fifo_client
|
||||||
|
rm -f input1.txt input2.txt input3.txt
|
||||||
|
rm -f output*.txt
|
||||||
|
rm -f /tmp/fifo_request /tmp/fifo_response
|
||||||
|
|
||||||
|
# Help
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " fifo - Compile fifo_server and fifo_client"
|
||||||
|
@echo " files - Create test input files"
|
||||||
|
@echo " test_server - Run FIFO server (use client in another terminal)"
|
||||||
|
@echo " test_client - Run FIFO client and show results"
|
||||||
|
@echo " clean - Remove built files and test files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all fifo files test_server test_client clean help
|
||||||
155
mine/lab_4/fifo_client.c
Normal file
155
mine/lab_4/fifo_client.c
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
#include <stdio.h> // printf, fprintf
|
||||||
|
#include <stdlib.h> // malloc, free, exit
|
||||||
|
#include <string.h> // strlen, strerror, strstr, sscanf
|
||||||
|
#include <unistd.h> // read, write, close, getpid
|
||||||
|
#include <fcntl.h> // open, O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC
|
||||||
|
#include <sys/types.h> // типы для системных вызовов
|
||||||
|
#include <sys/stat.h> // константы прав доступа (S_IRUSR и т.п.)
|
||||||
|
#include <errno.h> // errno и коды ошибок [web:17]
|
||||||
|
|
||||||
|
#define FIFO_REQUEST "/tmp/fifo_request" // путь к FIFO для запроса клиент→сервер
|
||||||
|
#define FIFO_RESPONSE "/tmp/fifo_response" // путь к FIFO для ответа сервер→клиент
|
||||||
|
#define BUFFER_SIZE 4096 // размер буфера для обмена данными
|
||||||
|
|
||||||
|
// Печать подсказки по использованию программы
|
||||||
|
void print_usage(const char *progname) {
|
||||||
|
fprintf(stderr, "Usage: %s <input_file> <output_file>\n", progname);
|
||||||
|
fprintf(stderr, "Example: %s input.txt output.txt\n", progname);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// Проверка числа аргументов командной строки
|
||||||
|
if (argc != 3) {
|
||||||
|
fprintf(stderr, "ERROR: Неверное количество аргументов\n");
|
||||||
|
print_usage(argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Имена входного и выходного файлов берём из аргументов
|
||||||
|
const char *input_file = argv[1];
|
||||||
|
const char *output_file = argv[2];
|
||||||
|
|
||||||
|
// Информационное сообщение о запуске клиента
|
||||||
|
printf("=== FIFO Client ===\n");
|
||||||
|
printf("Client PID: %d\n", getpid());
|
||||||
|
printf("Входной файл: %s\n", input_file);
|
||||||
|
printf("Выходной файл: %s\n", output_file);
|
||||||
|
|
||||||
|
// Открываем входной файл для чтения
|
||||||
|
int in_fd = open(input_file, O_RDONLY);
|
||||||
|
if (in_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть входной файл %s: %s\n",
|
||||||
|
input_file, strerror(errno));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выделяем буфер под содержимое файла и обмен с сервером
|
||||||
|
char *buffer = malloc(BUFFER_SIZE);
|
||||||
|
if (!buffer) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось выделить память\n");
|
||||||
|
close(in_fd);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Читаем данные из входного файла (не более BUFFER_SIZE-1, оставляем место под '\0')
|
||||||
|
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE - 1);
|
||||||
|
close(in_fd);
|
||||||
|
|
||||||
|
if (bytes_read < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось прочитать файл: %s\n", strerror(errno));
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Делаем буфер временно C-строкой для отладочного вывода
|
||||||
|
buffer[bytes_read] = '\0';
|
||||||
|
printf("Прочитано байт из файла: %zd\n", bytes_read);
|
||||||
|
|
||||||
|
// Открываем FIFO запроса на запись (ожидается, что сервер уже создал FIFO и слушает)
|
||||||
|
printf("Отправка запроса серверу...\n");
|
||||||
|
int fd_req = open(FIFO_REQUEST, O_WRONLY);
|
||||||
|
if (fd_req == -1) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть FIFO запроса: %s\n", strerror(errno));
|
||||||
|
fprintf(stderr, "Убедитесь, что сервер запущен!\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем прочитанные из файла данные серверу по FIFO запроса
|
||||||
|
ssize_t bytes_written = write(fd_req, buffer, bytes_read);
|
||||||
|
close(fd_req);
|
||||||
|
|
||||||
|
if (bytes_written != bytes_read) {
|
||||||
|
fprintf(stderr, "ERROR: Ошибка отправки данных\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Отправлено байт: %zd\n", bytes_written);
|
||||||
|
|
||||||
|
// Открываем FIFO ответа на чтение, чтобы получить обработанные данные от сервера
|
||||||
|
printf("Ожидание ответа от сервера...\n");
|
||||||
|
int fd_resp = open(FIFO_RESPONSE, O_RDONLY);
|
||||||
|
if (fd_resp == -1) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть FIFO ответа: %s\n", strerror(errno));
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Читаем ответ сервера в тот же буфер
|
||||||
|
ssize_t response_bytes = read(fd_resp, buffer, BUFFER_SIZE - 1);
|
||||||
|
close(fd_resp);
|
||||||
|
|
||||||
|
if (response_bytes < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Ошибка чтения ответа\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Делает ответ строкой для поиска служебной части с количеством замен
|
||||||
|
buffer[response_bytes] = '\0';
|
||||||
|
printf("Получено байт от сервера: %zd\n", response_bytes);
|
||||||
|
|
||||||
|
// В протоколе ответа сервер дописывает в конец строку вида "\nREPLACEMENTS:<число>"
|
||||||
|
// Ищем начало этой служебной информации
|
||||||
|
char *replacements_info = strstr(buffer, "\nREPLACEMENTS:");
|
||||||
|
long long replacements = 0;
|
||||||
|
|
||||||
|
if (replacements_info) {
|
||||||
|
// Считываем количество замен из служебной части
|
||||||
|
sscanf(replacements_info, "\nREPLACEMENTS:%lld", &replacements);
|
||||||
|
// Обрезаем строку в месте начала служебной части, оставляя только полезные данные
|
||||||
|
*replacements_info = '\0';
|
||||||
|
// Пересчитываем длину полезных данных как количество байт до служебного блока
|
||||||
|
response_bytes = replacements_info - buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем (или создаём) выходной файл с правами rw-rw-rw-
|
||||||
|
int out_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
|
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
|
||||||
|
if (out_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть выходной файл %s: %s\n",
|
||||||
|
output_file, strerror(errno));
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Записываем в выходной файл только содержимое (без служебной части REPLACEMENTS)
|
||||||
|
ssize_t written = write(out_fd, buffer, response_bytes);
|
||||||
|
close(out_fd);
|
||||||
|
|
||||||
|
if (written != response_bytes) {
|
||||||
|
fprintf(stderr, "ERROR: Ошибка записи в выходной файл\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Информационные сообщения об успешной обработке
|
||||||
|
printf("Записано байт в выходной файл: %zd\n", written);
|
||||||
|
printf("Количество выполненных замен: %lld\n", replacements);
|
||||||
|
printf("\nОбработка завершена успешно!\n");
|
||||||
|
|
||||||
|
// Освобождение выделенной памяти и нормальное завершение
|
||||||
|
free(buffer);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
206
mine/lab_4/fifo_server.c
Normal file
206
mine/lab_4/fifo_server.c
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
#include <stdio.h> // printf, fprintf
|
||||||
|
#include <stdlib.h> // malloc, free, strtoll
|
||||||
|
#include <string.h> // strlen, strerror
|
||||||
|
#include <unistd.h> // read, write, close, unlink, getpid
|
||||||
|
#include <fcntl.h> // open, флаги O_RDONLY/O_WRONLY
|
||||||
|
#include <sys/types.h> // типы для системных вызовов
|
||||||
|
#include <sys/stat.h> // mkfifo, права доступа
|
||||||
|
#include <errno.h> // errno
|
||||||
|
#include <signal.h> // signal, SIGINT, SIGTERM
|
||||||
|
|
||||||
|
#define FIFO_REQUEST "/tmp/fifo_request" // путь к FIFO для запроса клиент→сервер
|
||||||
|
#define FIFO_RESPONSE "/tmp/fifo_response" // путь к FIFO для ответа сервер→клиент
|
||||||
|
#define BUFFER_SIZE 4096 // размер буфера для обмена данными
|
||||||
|
|
||||||
|
// Флаг для аккуратного завершения по сигналу
|
||||||
|
volatile sig_atomic_t running = 1;
|
||||||
|
|
||||||
|
// Обработчик сигналов завершения (Ctrl+C, SIGTERM)
|
||||||
|
void signal_handler(int sig) {
|
||||||
|
(void) sig; // чтобы не ругался компилятор на неиспользуемый arg
|
||||||
|
running = 0; // помечаем, что надо выйти из основного цикла
|
||||||
|
}
|
||||||
|
|
||||||
|
// Разбор аргумента командной строки как неотрицательного long long
|
||||||
|
static long long parse_ll(const char *s) {
|
||||||
|
char *end = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long long v = strtoll(s, &end, 10);
|
||||||
|
// Проверяем: ошибка конверсии, пустая строка, лишние символы или отрицательное число
|
||||||
|
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Основная логика обработки текста:
|
||||||
|
// - input/input_len: входные данные
|
||||||
|
// - output/output_size: буфер для результата
|
||||||
|
// - max_replacements: глобальное ограничение по числу замен
|
||||||
|
// Правило: в каждой строке первый символ принят как "ключ" строки,
|
||||||
|
// все его повторения в этой строке заменяются на пробел (пока не кончится лимит).
|
||||||
|
long long process_data(const char *input, size_t input_len, char *output,
|
||||||
|
size_t output_size, long long max_replacements) {
|
||||||
|
long long total_replacements = 0; // сколько замен уже сделано
|
||||||
|
int at_line_start = 1; // находимся ли в начале строки
|
||||||
|
unsigned char line_key = 0; // символ-ключ для текущей строки
|
||||||
|
size_t out_pos = 0; // позиция записи в выходном буфере
|
||||||
|
|
||||||
|
// Идём по входным байтам, следим за пределами выходного буфера
|
||||||
|
for (size_t i = 0; i < input_len && out_pos < output_size - 1; i++) {
|
||||||
|
unsigned char c = (unsigned char) input[i];
|
||||||
|
|
||||||
|
// В начале строки первый символ становится ключом строки
|
||||||
|
if (at_line_start) {
|
||||||
|
line_key = c;
|
||||||
|
at_line_start = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned char outc = c;
|
||||||
|
|
||||||
|
// Если встретили перевод строки — следующая позиция снова "начало строки"
|
||||||
|
if (c == '\n') {
|
||||||
|
at_line_start = 1;
|
||||||
|
}
|
||||||
|
// Если символ равен ключу строки и лимит замен ещё не исчерпан —
|
||||||
|
// заменяем его на пробел и увеличиваем счётчик
|
||||||
|
else if (c == line_key && total_replacements < max_replacements) {
|
||||||
|
outc = ' ';
|
||||||
|
total_replacements++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Записываем преобразованный символ в выходной буфер
|
||||||
|
output[out_pos++] = (char) outc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Добавляем завершающий ноль, чтобы удобнее работать как со строкой
|
||||||
|
output[out_pos] = '\0';
|
||||||
|
return total_replacements;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// Ожидаем один аргумент: max_replacements
|
||||||
|
if (argc != 2) {
|
||||||
|
fprintf(stderr, "Usage: %s <max_replacements>\n", argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Парсим максимальное количество замен
|
||||||
|
long long max_replacements = parse_ll(argv[1]);
|
||||||
|
if (max_replacements < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Invalid max_replacements\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Информационный вывод о запуске сервера
|
||||||
|
printf("=== FIFO Server запущен ===\n");
|
||||||
|
printf("Server PID: %d\n", getpid());
|
||||||
|
printf("Максимум замен: %lld\n", max_replacements);
|
||||||
|
|
||||||
|
// Устанавливаем обработчики сигналов для корректного завершения
|
||||||
|
signal(SIGINT, signal_handler);
|
||||||
|
signal(SIGTERM, signal_handler);
|
||||||
|
// Не умирать от SIGPIPE, когда клиент закрыл FIFO
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
|
||||||
|
// На всякий случай удаляем старые FIFO, если остались от предыдущего запуска
|
||||||
|
unlink(FIFO_REQUEST);
|
||||||
|
unlink(FIFO_RESPONSE);
|
||||||
|
|
||||||
|
// Создаем именованный канал для запросов
|
||||||
|
if (mkfifo(FIFO_REQUEST, 0666) == -1) {
|
||||||
|
perror("mkfifo request");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
// Создаем именованный канал для ответов
|
||||||
|
if (mkfifo(FIFO_RESPONSE, 0666) == -1) {
|
||||||
|
perror("mkfifo response");
|
||||||
|
unlink(FIFO_REQUEST); // чистим первый, если второй mkfifo не удался
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("FIFO каналы созданы:\n");
|
||||||
|
printf(" Request: %s\n", FIFO_REQUEST);
|
||||||
|
printf(" Response: %s\n", FIFO_RESPONSE);
|
||||||
|
printf("Ожидание запросов от клиентов...\n\n");
|
||||||
|
|
||||||
|
// Главный цикл сервера: пока не пришёл сигнал завершения
|
||||||
|
while (running) {
|
||||||
|
// Открываем FIFO запроса для чтения (блокируется, пока клиент не откроет на запись)
|
||||||
|
int fd_req = open(FIFO_REQUEST, O_RDONLY);
|
||||||
|
if (fd_req == -1) {
|
||||||
|
// Если нас прервали сигналом, просто пробуем снова
|
||||||
|
if (errno == EINTR) continue;
|
||||||
|
perror("open request FIFO");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выделяем буферы под входные и выходные данные для текущего запроса
|
||||||
|
char *input_buffer = malloc(BUFFER_SIZE);
|
||||||
|
char *output_buffer = malloc(BUFFER_SIZE);
|
||||||
|
|
||||||
|
if (!input_buffer || !output_buffer) {
|
||||||
|
fprintf(stderr, "ERROR: Memory allocation failed\n");
|
||||||
|
close(fd_req);
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Читаем данные от клиента
|
||||||
|
ssize_t bytes_read = read(fd_req, input_buffer, BUFFER_SIZE - 1);
|
||||||
|
close(fd_req);
|
||||||
|
|
||||||
|
// Если ничего не прочитали или ошибка — просто переходим к следующему циклу
|
||||||
|
if (bytes_read <= 0) {
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Делаем входной буфер C-строкой для удобства отладки
|
||||||
|
input_buffer[bytes_read] = '\0';
|
||||||
|
printf("Получен запрос: %zd байт\n", bytes_read);
|
||||||
|
|
||||||
|
// Обрабатываем данные по заданному правилу
|
||||||
|
long long replacements = process_data(input_buffer, bytes_read,
|
||||||
|
output_buffer, BUFFER_SIZE,
|
||||||
|
max_replacements);
|
||||||
|
|
||||||
|
printf("Выполнено замен: %lld\n", replacements);
|
||||||
|
|
||||||
|
// Открываем FIFO ответа для записи (ждём, пока клиент откроет на чтение)
|
||||||
|
int fd_resp = open(FIFO_RESPONSE, O_WRONLY);
|
||||||
|
if (fd_resp == -1) {
|
||||||
|
perror("open response FIFO");
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем клиенту обработанный текст
|
||||||
|
size_t output_len = strlen(output_buffer);
|
||||||
|
ssize_t bytes_written = write(fd_resp, output_buffer, output_len);
|
||||||
|
|
||||||
|
// Затем — служебную строку с количеством замен в формате "\nREPLACEMENTS:<n>\n"
|
||||||
|
char result[64];
|
||||||
|
snprintf(result, sizeof(result), "\nREPLACEMENTS:%lld\n", replacements);
|
||||||
|
write(fd_resp, result, strlen(result));
|
||||||
|
|
||||||
|
// Закрываем FIFO ответа — завершение "сессии" с клиентом
|
||||||
|
close(fd_resp);
|
||||||
|
|
||||||
|
printf("Отправлен ответ: %zd байт\n\n", bytes_written);
|
||||||
|
|
||||||
|
// Освобождаем буферы для этого запроса
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// При завершении работы сервера удаляем FIFO
|
||||||
|
printf("\nЗавершение работы сервера...\n");
|
||||||
|
unlink(FIFO_REQUEST);
|
||||||
|
unlink(FIFO_RESPONSE);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
60
mine/lab_5/Makefile
Normal file
60
mine/lab_5/Makefile
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_MQ = -lrt
|
||||||
|
|
||||||
|
# SERVER_ARGS: <total_honey> <portion> <period_ms> <starvation_ms>
|
||||||
|
# WORKER_ARGS: <honey_portion>
|
||||||
|
SERVER_ARGS = 1000 15 500 500
|
||||||
|
WORKER_ARGS = 7
|
||||||
|
|
||||||
|
all: msg
|
||||||
|
|
||||||
|
# ===== POSIX MQ targets =====
|
||||||
|
msg: msg_server msg_worker
|
||||||
|
|
||||||
|
msg_server: server.c common.h
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
msg_worker: worker.c common.h
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
# ===== Tests =====
|
||||||
|
test_msg_server: msg
|
||||||
|
@echo "=== Запуск сервера POSIX MQ ==="
|
||||||
|
@echo "В другом терминале выполните: make test_msg_workers"
|
||||||
|
./msg_server $(SERVER_ARGS)
|
||||||
|
|
||||||
|
test_msg_workers: msg
|
||||||
|
@echo "=== Запуск нескольких пчёл ==="
|
||||||
|
./msg_worker 7 & \
|
||||||
|
./msg_worker 9 & \
|
||||||
|
./msg_worker 5 & \
|
||||||
|
wait
|
||||||
|
|
||||||
|
# Автотест: сервер в фоне, несколько пчёл
|
||||||
|
test_all: msg
|
||||||
|
@echo "=== Автотест POSIX MQ ==="
|
||||||
|
./msg_server $(SERVER_ARGS) & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 2; \
|
||||||
|
./msg_worker $(WORKER_ARGS) & \
|
||||||
|
./msg_worker $(WORKER_ARGS) & \
|
||||||
|
./msg_worker $(WORKER_ARGS) & \
|
||||||
|
wait; \
|
||||||
|
wait $$SRV
|
||||||
|
|
||||||
|
# Очистка
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f msg_server msg_worker
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " msg - Build POSIX message queue programs"
|
||||||
|
@echo " test_msg_server - Run MQ server (use workers in another terminal)"
|
||||||
|
@echo " test_msg_workers - Run several worker processes"
|
||||||
|
@echo " test_all - Automatic end-to-end test"
|
||||||
|
@echo " clean - Remove built files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all msg test_msg_server test_msg_workers test_all clean help
|
||||||
16
mine/lab_5/common.h
Normal file
16
mine/lab_5/common.h
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#define REQ_QUEUE "/winnie_req"
|
||||||
|
#define NAME_MAXLEN 64
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
pid_t pid;
|
||||||
|
int want;
|
||||||
|
char replyq[NAME_MAXLEN];
|
||||||
|
} req_msg_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int granted;
|
||||||
|
int remain;
|
||||||
|
} rep_msg_t;
|
||||||
230
mine/lab_5/server.c
Normal file
230
mine/lab_5/server.c
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
#define _GNU_SOURCE // для определения расширенных возможностей glibc
|
||||||
|
#include <errno.h>
|
||||||
|
#include <mqueue.h> // POSIX очереди сообщений: mq_open, mq_send, mq_receive, mq_timedreceive
|
||||||
|
#include <signal.h> // sig_atomic_t, signal, SIGINT
|
||||||
|
#include <stdbool.h> // bool, true/false
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h> // printf, fprintf, perror
|
||||||
|
#include <stdlib.h> // atoi, malloc/free при желании
|
||||||
|
#include <string.h> // memset, strncpy, strncmp
|
||||||
|
#include <sys/stat.h> // константы прав доступа к объектам ФС
|
||||||
|
#include <time.h> // clock_gettime, nanosleep, struct timespec
|
||||||
|
|
||||||
|
#include "common.h" // описания REQ_QUEUE, NAME_MAXLEN, req_msg_t, rep_msg_t и т.п.
|
||||||
|
|
||||||
|
#ifndef MAX_CLIENTS
|
||||||
|
#define MAX_CLIENTS 128 // максимальное число клиентов, чьи очереди мы запомним
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Глобальный флаг остановки сервера по сигналу
|
||||||
|
static volatile sig_atomic_t stop_flag = 0;
|
||||||
|
// Обработчик SIGINT: просто выставляет флаг
|
||||||
|
static void on_sigint(int) { stop_flag = 1; }
|
||||||
|
|
||||||
|
// Удобная функция "уснуть" на ms миллисекунд
|
||||||
|
static void msleep(int ms) {
|
||||||
|
struct timespec ts = {
|
||||||
|
.tv_sec = ms / 1000,
|
||||||
|
.tv_nsec = (ms % 1000) * 1000000L
|
||||||
|
};
|
||||||
|
nanosleep(&ts, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Простейший реестр клиентов: массив имён их ответных очередей */
|
||||||
|
static char clients[MAX_CLIENTS][NAME_MAXLEN];
|
||||||
|
static int client_count = 0;
|
||||||
|
|
||||||
|
// Добавляет имя очереди клиента в список, если его там ещё нет
|
||||||
|
static void add_client(const char *name) {
|
||||||
|
if (!name || name[0] == '\0') return;
|
||||||
|
// Проверка на дубликат
|
||||||
|
for (int i = 0; i < client_count; ++i) {
|
||||||
|
if (strncmp(clients[i], name, NAME_MAXLEN) == 0) return;
|
||||||
|
}
|
||||||
|
// Если есть место — копируем имя в массив
|
||||||
|
if (client_count < MAX_CLIENTS) {
|
||||||
|
strncpy(clients[client_count], name, NAME_MAXLEN - 1);
|
||||||
|
clients[client_count][NAME_MAXLEN - 1] = '\0';
|
||||||
|
client_count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Рассылает всем запомненным клиентам сообщение STOP (granted=0, remain=0) */
|
||||||
|
static void send_stop_to_clients(void) {
|
||||||
|
rep_msg_t stoprep;
|
||||||
|
memset(&stoprep, 0, sizeof(stoprep));
|
||||||
|
stoprep.granted = 0;
|
||||||
|
stoprep.remain = 0;
|
||||||
|
|
||||||
|
for (int i = 0; i < client_count; ++i) {
|
||||||
|
// Открываем очередь ответа клиента только на запись
|
||||||
|
mqd_t q = mq_open(clients[i], O_WRONLY);
|
||||||
|
if (q == -1) {
|
||||||
|
// Лучшая попытка: если открыть не удалось — просто пропускаем
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Отправляем структуру-ответ без приоритета (0)
|
||||||
|
mq_send(q, (const char *) &stoprep, sizeof(stoprep), 0);
|
||||||
|
mq_close(q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
// Ожидается: total_honey, portion, period_ms, starvation_ms
|
||||||
|
if (argc != 5) {
|
||||||
|
fprintf(stderr, "Usage: %s <total_honey> <portion> <period_ms> <starvation_ms>\n", argv[0]);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Разбираем параметры симуляции
|
||||||
|
int remain = atoi(argv[1]); // сколько "мёда" всего
|
||||||
|
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) {
|
||||||
|
fprintf(stderr, "Bad args\n");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// На всякий случай удаляем старую очередь запросов, если осталась
|
||||||
|
mq_unlink(REQ_QUEUE);
|
||||||
|
|
||||||
|
// Настроиваем атрибуты очереди запросов
|
||||||
|
struct mq_attr attr;
|
||||||
|
memset(&attr, 0, sizeof(attr));
|
||||||
|
attr.mq_maxmsg = 10; // максимум 10 сообщений в очереди
|
||||||
|
attr.mq_msgsize = sizeof(req_msg_t); // размер одного сообщения = размер структуры запроса
|
||||||
|
|
||||||
|
// Открываем общую очередь запросов: создаём и даём читать/писать
|
||||||
|
// (читаем заявки и также сможем через неё послать STOP при желании)
|
||||||
|
mqd_t qreq = mq_open(REQ_QUEUE, O_CREAT | O_RDWR, 0666, &attr);
|
||||||
|
if (qreq == (mqd_t) -1) {
|
||||||
|
perror("mq_open qreq");
|
||||||
|
fprintf(stderr, "Hint: ensure msg_max>=10 and msgsize_max>=%zu\n", sizeof(req_msg_t));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для отладки выводим реальные атрибуты очереди
|
||||||
|
struct mq_attr got;
|
||||||
|
if (mq_getattr(qreq, &got) == 0) {
|
||||||
|
fprintf(stderr, "Server: q=%s maxmsg=%ld msgsize=%ld cur=%ld\n",
|
||||||
|
REQ_QUEUE, got.mq_maxmsg, got.mq_msgsize, got.mq_curmsgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обработчик Ctrl+C: аккуратное завершение
|
||||||
|
signal(SIGINT, on_sigint);
|
||||||
|
|
||||||
|
fprintf(stderr, "Server: started remain=%d portion=%d period=%dms starve=%dms\n",
|
||||||
|
remain, portion, period_ms, starvation_ms);
|
||||||
|
|
||||||
|
// Инициализируем "текущее время" и моменты следующего приёма пищи / последней еды
|
||||||
|
struct timespec now;
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
|
long long now_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; // буфер для входящего запроса
|
||||||
|
bool need_stop_broadcast = false; // флаг: нужно ли разослать клиентам STOP
|
||||||
|
|
||||||
|
// Главный цикл сервера: обрабатываем запросы и "еду" до сигнала или окончания мёда
|
||||||
|
while (!stop_flag) {
|
||||||
|
// Обновляем текущее время
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
|
now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
||||||
|
|
||||||
|
// Сколько мс до следующего приёма пищи
|
||||||
|
int sleep_ms = (int) ((next_eat_ns - now_ns) / 1000000LL);
|
||||||
|
if (sleep_ms < 0) sleep_ms = 0;
|
||||||
|
|
||||||
|
// Дедлайн для mq_timedreceive: ждём сообщение не дольше sleep_ms
|
||||||
|
struct timespec deadline = {
|
||||||
|
.tv_sec = now.tv_sec + sleep_ms / 1000,
|
||||||
|
.tv_nsec = now.tv_nsec + (sleep_ms % 1000) * 1000000L
|
||||||
|
};
|
||||||
|
if (deadline.tv_nsec >= 1000000000L) {
|
||||||
|
deadline.tv_sec++;
|
||||||
|
deadline.tv_nsec -= 1000000000L;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Пытаемся принять запрос до наступления дедлайна
|
||||||
|
ssize_t rd = mq_timedreceive(qreq, (char *) &req, sizeof(req), NULL, &deadline);
|
||||||
|
if (rd >= 0) {
|
||||||
|
// Успешно прочитали структуру запроса
|
||||||
|
if (req.want != 0) {
|
||||||
|
// Регистрируем очередь ответа клиента, чтобы уметь послать ему STOP
|
||||||
|
add_client(req.replyq);
|
||||||
|
|
||||||
|
rep_msg_t rep;
|
||||||
|
if (remain > 0) {
|
||||||
|
int grant = req.want;
|
||||||
|
if (grant > remain) grant = remain;
|
||||||
|
remain -= grant;
|
||||||
|
rep.granted = grant; // сколько реально дали
|
||||||
|
rep.remain = remain; // сколько осталось
|
||||||
|
} else {
|
||||||
|
// Мёд закончился — ничего не даём
|
||||||
|
rep.granted = 0;
|
||||||
|
rep.remain = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем очередь ответа клиента и отправляем ему ответ
|
||||||
|
mqd_t qrep = mq_open(req.replyq, O_WRONLY);
|
||||||
|
if (qrep != (mqd_t) -1) {
|
||||||
|
mq_send(qrep, (const char *) &rep, sizeof(rep), 0);
|
||||||
|
mq_close(qrep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (errno != ETIMEDOUT && errno != EAGAIN) {
|
||||||
|
// Любая ошибка, кроме "таймаут" или "временно нет сообщений", логируется
|
||||||
|
perror("mq_timedreceive");
|
||||||
|
}
|
||||||
|
|
||||||
|
// После приёма (или таймаута) обновляем текущее время и проверяем, пора ли Винни есть
|
||||||
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||||
|
now_ns = (long long) now.tv_sec * 1000000000LL + now.tv_nsec;
|
||||||
|
|
||||||
|
if (now_ns >= next_eat_ns) {
|
||||||
|
if (remain > 0) {
|
||||||
|
// Винни ест свою порцию (или остаток, если мёда меньше порции)
|
||||||
|
int eat = portion;
|
||||||
|
if (eat > remain) eat = remain;
|
||||||
|
remain -= eat;
|
||||||
|
last_feed_ns = now_ns;
|
||||||
|
fprintf(stderr, "Winnie eats %d, remain=%d\n", eat, remain);
|
||||||
|
} else {
|
||||||
|
// Мёда нет: проверяем, не умер ли Винни с голоду (starvation_ms)
|
||||||
|
if (starvation_ms > 0 &&
|
||||||
|
(now_ns - last_feed_ns) / 1000000LL >= starvation_ms) {
|
||||||
|
fprintf(stderr, "Winnie starved, stopping\n");
|
||||||
|
need_stop_broadcast = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Планируем следующий приём пищи через period_ms
|
||||||
|
next_eat_ns = now_ns + (long long) period_ms * 1000000LL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если мёд закончился, надо будет всем сообщить STOP и завершаться
|
||||||
|
if (remain <= 0) {
|
||||||
|
need_stop_broadcast = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// При нормальном окончании (мёд закончился или Винни умер с голоду)
|
||||||
|
// посылаем всем клиентам STOP
|
||||||
|
if (need_stop_broadcast) {
|
||||||
|
fprintf(stderr, "Server: broadcasting STOP to clients\n");
|
||||||
|
send_stop_to_clients();
|
||||||
|
msleep(100); // даём клиентам время получить сообщение
|
||||||
|
}
|
||||||
|
|
||||||
|
// Закрываем и удаляем очередь запросов
|
||||||
|
mq_close(qreq);
|
||||||
|
mq_unlink(REQ_QUEUE);
|
||||||
|
|
||||||
|
fprintf(stderr, "Server: finished\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
123
mine/lab_5/worker.c
Normal file
123
mine/lab_5/worker.c
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
#define _GNU_SOURCE // для определения расширенных возможностей glibc
|
||||||
|
#include <errno.h>
|
||||||
|
#include <mqueue.h> // POSIX очереди сообщений: mq_open, mq_send, mq_receive
|
||||||
|
#include <signal.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h> // fprintf, perror, dprintf
|
||||||
|
#include <stdlib.h> // atoi, rand_r
|
||||||
|
#include <string.h> // memset, strncpy, snprintf
|
||||||
|
#include <sys/stat.h> // права для mq_open (0666)
|
||||||
|
#include <time.h> // time(), nanosleep, struct timespec
|
||||||
|
#include <unistd.h> // getpid, STDOUT_FILENO
|
||||||
|
|
||||||
|
#include "common.h" // REQ_QUEUE, NAME_MAXLEN, req_msg_t, rep_msg_t
|
||||||
|
|
||||||
|
// Пауза на заданное количество миллисекунд
|
||||||
|
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 пчелы и имя её личной очереди ответов
|
||||||
|
pid_t me = getpid();
|
||||||
|
char replyq[NAME_MAXLEN];
|
||||||
|
snprintf(replyq, sizeof(replyq), "/bee_%d", (int) me);
|
||||||
|
|
||||||
|
// На всякий случай удаляем старую очередь с таким именем
|
||||||
|
mq_unlink(replyq);
|
||||||
|
|
||||||
|
// Атрибуты очереди ответов (куда сервер будет слать rep_msg_t)
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем очередь запросов к серверу (общая очередь REQ_QUEUE)
|
||||||
|
mqd_t qreq = -1;
|
||||||
|
for (int i = 0; i < 50; i++) {
|
||||||
|
qreq = mq_open(REQ_QUEUE, O_WRONLY);
|
||||||
|
if (qreq != -1) break; // удалось открыть — выходим из цикла
|
||||||
|
if (errno != ENOENT) {
|
||||||
|
// другая ошибка, не "очередь ещё не создана"
|
||||||
|
perror("mq_open req");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// Если сервер ещё не создал очередь (ENOENT) — подождать и попробовать снова
|
||||||
|
msleep(100);
|
||||||
|
}
|
||||||
|
if (qreq == -1) {
|
||||||
|
// Не смогли открыть очередь запросов — выходим
|
||||||
|
perror("mq_open req");
|
||||||
|
mq_close(qrep);
|
||||||
|
mq_unlink(replyq);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Инициализация отдельного генератора случайных чисел для этой пчелы
|
||||||
|
unsigned seed = (unsigned) (time(NULL) ^ (uintptr_t) me);
|
||||||
|
|
||||||
|
// Основной рабочий цикл пчелы
|
||||||
|
while (1) {
|
||||||
|
// Ждём случайное время 100–699 мс перед очередным запросом
|
||||||
|
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); // куда слать ответ
|
||||||
|
|
||||||
|
// Отправляем запрос в очередь REQ_QUEUE
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если нам больше ничего не дают (granted <= 0) — выходим
|
||||||
|
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;
|
||||||
|
}
|
||||||
62
mine/lab_6/Makefile
Normal file
62
mine/lab_6/Makefile
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
# Makefile для лабораторной: POSIX shared memory + POSIX semaphores. [file:21][web:47]
|
||||||
|
# Сервер сам чистит старые IPC-объекты и корректно завершает работу. [file:21]
|
||||||
|
|
||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_IPC = -lrt -pthread
|
||||||
|
|
||||||
|
# Аргументы IPC: <shm_name> <sem_client_name> <sem_server_name> [iterations]. [file:21]
|
||||||
|
SHM_NAME ?= /myshm
|
||||||
|
SEM_CLIENT_NAME ?= /sem_client
|
||||||
|
SEM_SERVER_NAME ?= /sem_server
|
||||||
|
SERVER_ITERS ?= 1000
|
||||||
|
|
||||||
|
all: shm # Цель по умолчанию: сборка server и client. [file:22]
|
||||||
|
|
||||||
|
# ===== Сборка программ POSIX SHM + SEM =====
|
||||||
|
shm: server client # Группа целей для IPC-программ. [file:21]
|
||||||
|
|
||||||
|
server: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC) # Сборка сервера. [file:21][web:47]
|
||||||
|
|
||||||
|
client: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC) # Сборка клиента. [file:21][web:47]
|
||||||
|
|
||||||
|
# ===== Тесты =====
|
||||||
|
|
||||||
|
# Ручной тест: сервер в одном терминале, клиент в другом. [file:22]
|
||||||
|
test_server: shm
|
||||||
|
@echo "=== Запуск сервера POSIX SHM+SEM ==="
|
||||||
|
@echo "В другом терминале выполните: make test_client"
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS)
|
||||||
|
|
||||||
|
# Клиент: читает input.txt, выводит обработанные строки в stdout. [file:22]
|
||||||
|
test_client: shm
|
||||||
|
@echo "=== Запуск клиента, чтение input.txt, вывод на stdout ==="
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME)
|
||||||
|
|
||||||
|
# Автотест: сервер в фоне, клиент один раз читает input.txt. [file:22]
|
||||||
|
test_all: shm
|
||||||
|
@echo "=== Автотест POSIX SHM+SEM с файлами input.txt/output.txt ==="
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS) & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME); \
|
||||||
|
wait $$SRV
|
||||||
|
|
||||||
|
# Очистка бинарников и файлов (IPC‑объекты чистит сам сервер). [file:21]
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f server client
|
||||||
|
rm -f output.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " shm - Build POSIX SHM+SEM programs"
|
||||||
|
@echo " test_server - Run SHM+SEM server (client in another terminal)"
|
||||||
|
@echo " test_client - Run client reading input.txt"
|
||||||
|
@echo " test_all - Automatic end-to-end test with input.txt/output.txt"
|
||||||
|
@echo " clean - Remove built files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all shm test_server test_client test_all clean help
|
||||||
156
mine/lab_6/client.c
Normal file
156
mine/lab_6/client.c
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
// Клиент POSIX IPC: читает строки из input.txt, передаёт их серверу через
|
||||||
|
// POSIX shared memory и синхронизируется с сервером через именованные семафоры.
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/mman.h> // shm_open, mmap, munmap — POSIX разделяемая память
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <semaphore.h> // sem_open, sem_close, sem_wait, sem_post — POSIX семафоры
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
// Размер буфера обмена (должен совпадать с server.c).
|
||||||
|
#define SHM_BUFFER_SIZE 1024
|
||||||
|
|
||||||
|
// Структура, находящаяся в POSIX shared memory.
|
||||||
|
typedef struct {
|
||||||
|
int has_data;
|
||||||
|
int result_code;
|
||||||
|
char buffer[SHM_BUFFER_SIZE];
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// argv[1] - имя POSIX shared memory (должно совпадать с сервером).
|
||||||
|
// argv[2] - имя именованного семафора клиента.
|
||||||
|
// argv[3] - имя именованного семафора сервера.
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name>\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *shm_name = argv[1];
|
||||||
|
const char *sem_client_name = argv[2];
|
||||||
|
const char *sem_server_name = argv[3];
|
||||||
|
|
||||||
|
// Открываем существующий объект POSIX shared memory, созданный сервером (shm_open).
|
||||||
|
int shm_fd = shm_open(shm_name, O_RDWR, 0);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отображаем POSIX shared memory в адресное пространство клиента (mmap с MAP_SHARED).
|
||||||
|
shared_block_t *shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
close(shm_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// После успешного mmap файловый дескриптор POSIX shared memory можно закрыть.
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем именованные POSIX семафоры, которые создал сервер (sem_open).
|
||||||
|
sem_t *sem_client = sem_open(sem_client_name, 0);
|
||||||
|
if (sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_server = sem_open(sem_server_name, 0);
|
||||||
|
if (sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
FILE *fin = fopen("input.txt", "r");
|
||||||
|
if (!fin) {
|
||||||
|
perror("fopen(input.txt)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char input[SHM_BUFFER_SIZE];
|
||||||
|
|
||||||
|
while (fgets(input, sizeof(input), fin) != NULL) {
|
||||||
|
size_t len = strlen(input);
|
||||||
|
|
||||||
|
if (len > 0 && input[len - 1] == '\n') {
|
||||||
|
input[len - 1] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
|
||||||
|
strncpy(shm_ptr->buffer, input, SHM_BUFFER_SIZE - 1);
|
||||||
|
shm_ptr->buffer[SHM_BUFFER_SIZE - 1] = '\0';
|
||||||
|
|
||||||
|
shm_ptr->has_data = 1;
|
||||||
|
|
||||||
|
// Клиент увеличивает семафор клиента (sem_post), разблокируя сервер (sem_wait).
|
||||||
|
if (sem_post(sem_client) == -1) {
|
||||||
|
perror("sem_post(sem_client)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Клиент блокируется на семафоре сервера (sem_wait), пока сервер не закончит обработку.
|
||||||
|
if (sem_wait(sem_server) == -1) {
|
||||||
|
perror("sem_wait(sem_server)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shm_ptr->result_code != 0) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Server reported error, result_code = %d\n",
|
||||||
|
shm_ptr->result_code);
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%s\n", shm_ptr->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fin) == EOF) {
|
||||||
|
perror("fclose(input.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Закрываем дескрипторы POSIX семафоров в процессе клиента (sem_close).
|
||||||
|
if (sem_close(sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_close(sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отсоединяем отображённую область POSIX shared memory (munmap).
|
||||||
|
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
6
mine/lab_6/input.txt
Normal file
6
mine/lab_6/input.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
abacaba
|
||||||
|
xxxxxx
|
||||||
|
hello
|
||||||
|
aaaaa
|
||||||
|
1abc1d1e1
|
||||||
|
qwerty
|
||||||
286
mine/lab_6/server.c
Normal file
286
mine/lab_6/server.c
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
// Сервер POSIX IPC: использует POSIX shared memory (shm_open + mmap)
|
||||||
|
// и именованные POSIX семафоры (sem_open, sem_wait, sem_post) для обмена с клиентом.
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <fcntl.h> // O_CREAT, O_EXCL, O_RDWR для shm_open
|
||||||
|
#include <sys/mman.h> // shm_open, mmap, munmap — POSIX разделяемая память
|
||||||
|
#include <sys/stat.h> // Права доступа к объектам POSIX shared memory и семафорам
|
||||||
|
#include <semaphore.h> // POSIX именованные семафоры: sem_open, sem_close, sem_unlink, sem_wait, sem_post
|
||||||
|
#include <unistd.h> // ftruncate, close
|
||||||
|
#include <signal.h>
|
||||||
|
|
||||||
|
// Максимальная длина строки (включая '\0') для обмена через shared memory.
|
||||||
|
#define SHM_BUFFER_SIZE 1024
|
||||||
|
|
||||||
|
// Структура расположена целиком в POSIX shared memory и разделяется сервером и клиентом.
|
||||||
|
typedef struct {
|
||||||
|
int has_data;
|
||||||
|
int result_code;
|
||||||
|
char buffer[SHM_BUFFER_SIZE];
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
// Глобальные объекты, связанные с POSIX shared memory и семафорами.
|
||||||
|
static shared_block_t *g_shm_ptr = NULL; // Указатель на mmap(shared memory).
|
||||||
|
static char g_shm_name[256] = ""; // Имя объекта POSIX shared memory (для shm_unlink).
|
||||||
|
static char g_sem_client_name[256] = ""; // Имя именованного семафора клиента (sem_open/sem_unlink).
|
||||||
|
static char g_sem_server_name[256] = ""; // Имя именованного семафора сервера (sem_open/sem_unlink).
|
||||||
|
static sem_t *g_sem_client = NULL; // Дескриптор POSIX семафора клиента.
|
||||||
|
static sem_t *g_sem_server = NULL; // Дескриптор POSIX семафора сервера.
|
||||||
|
static FILE *g_fout = NULL;
|
||||||
|
|
||||||
|
// Обработчик сигналов завершения: корректно удаляет POSIX shared memory и семафоры.
|
||||||
|
static void handle_signal(int signo) {
|
||||||
|
(void) signo;
|
||||||
|
|
||||||
|
if (g_sem_client) {
|
||||||
|
sem_close(g_sem_client);
|
||||||
|
g_sem_client = NULL;
|
||||||
|
}
|
||||||
|
if (g_sem_server) {
|
||||||
|
sem_close(g_sem_server);
|
||||||
|
g_sem_server = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sem_unlink удаляет именованные POSIX семафоры из системы.
|
||||||
|
if (g_sem_client_name[0] != '\0') {
|
||||||
|
sem_unlink(g_sem_client_name);
|
||||||
|
}
|
||||||
|
if (g_sem_server_name[0] != '\0') {
|
||||||
|
sem_unlink(g_sem_server_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// munmap отсоединяет область POSIX shared memory из адресного пространства процесса.
|
||||||
|
if (g_shm_ptr) {
|
||||||
|
munmap(g_shm_ptr, sizeof(shared_block_t));
|
||||||
|
g_shm_ptr = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// shm_unlink удаляет объект POSIX shared memory.
|
||||||
|
if (g_shm_name[0] != '\0') {
|
||||||
|
shm_unlink(g_shm_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_fout) {
|
||||||
|
fclose(g_fout);
|
||||||
|
g_fout = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
_exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void process_line(char *s) {
|
||||||
|
if (s == NULL || s[0] == '\0') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
char first = s[0];
|
||||||
|
|
||||||
|
for (size_t i = 1; s[i] != '\0'; ++i) {
|
||||||
|
if (s[i] == first) {
|
||||||
|
s[i] = ' ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// argv[1] - имя POSIX shared memory (например, "/myshm").
|
||||||
|
// argv[2] - имя именованного семафора клиента (например, "/sem_client").
|
||||||
|
// argv[3] - имя именованного семафора сервера (например, "/sem_server").
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name> [iterations]\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
strncpy(g_shm_name, argv[1], sizeof(g_shm_name) - 1);
|
||||||
|
strncpy(g_sem_client_name, argv[2], sizeof(g_sem_client_name) - 1);
|
||||||
|
strncpy(g_sem_server_name, argv[3], sizeof(g_sem_server_name) - 1);
|
||||||
|
g_shm_name[sizeof(g_shm_name) - 1] = '\0';
|
||||||
|
g_sem_client_name[sizeof(g_sem_client_name) - 1] = '\0';
|
||||||
|
g_sem_server_name[sizeof(g_sem_server_name) - 1] = '\0';
|
||||||
|
|
||||||
|
const char *shm_name = g_shm_name;
|
||||||
|
const char *sem_client_name = g_sem_client_name;
|
||||||
|
const char *sem_server_name = g_sem_server_name;
|
||||||
|
|
||||||
|
int iterations = -1;
|
||||||
|
if (argc >= 5) {
|
||||||
|
char *endptr = NULL;
|
||||||
|
unsigned long tmp = strtoul(argv[4], &endptr, 10);
|
||||||
|
if (endptr == argv[4] || *endptr != '\0') {
|
||||||
|
fprintf(stderr, "Invalid iterations value: '%s'\n", argv[4]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
iterations = (int) tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
signal(SIGINT, handle_signal);
|
||||||
|
signal(SIGTERM, handle_signal);
|
||||||
|
|
||||||
|
// Удаляем старые объекты POSIX shared memory и семафоров, если они остались от прошлых запусков.
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
sem_unlink(sem_server_name);
|
||||||
|
|
||||||
|
// Создаём новый объект POSIX shared memory (shm_open с O_CREAT | O_EXCL | O_RDWR).
|
||||||
|
int shm_fd = shm_open(shm_name,
|
||||||
|
O_CREAT | O_EXCL | O_RDWR,
|
||||||
|
S_IRUSR | S_IWUSR);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ftruncate задаёт размер объекта POSIX shared memory под нашу структуру.
|
||||||
|
if (ftruncate(shm_fd, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("ftruncate");
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отображаем POSIX shared memory в адресное пространство сервера (mmap с MAP_SHARED).
|
||||||
|
g_shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (g_shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
g_shm_ptr = NULL;
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// После успешного mmap файловый дескриптор POSIX shared memory можно закрыть.
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
g_shm_ptr->has_data = 0;
|
||||||
|
g_shm_ptr->result_code = 0;
|
||||||
|
memset(g_shm_ptr->buffer, 0, sizeof(g_shm_ptr->buffer));
|
||||||
|
|
||||||
|
// Создаём именованный семафор клиента: клиент будет делать sem_post, сервер — sem_wait.
|
||||||
|
g_sem_client = sem_open(sem_client_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0); // начальное значение 0, сервер сразу блокируется на sem_wait.
|
||||||
|
if (g_sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
g_sem_client = NULL;
|
||||||
|
munmap(g_shm_ptr, sizeof(shared_block_t));
|
||||||
|
g_shm_ptr = NULL;
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создаём именованный семафор сервера: сервер делает sem_post, клиент — sem_wait.
|
||||||
|
g_sem_server = sem_open(sem_server_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0);
|
||||||
|
if (g_sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(g_sem_client);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
g_sem_client = NULL;
|
||||||
|
munmap(g_shm_ptr, sizeof(shared_block_t));
|
||||||
|
g_shm_ptr = NULL;
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_fout = fopen("output.txt", "w");
|
||||||
|
if (!g_fout) {
|
||||||
|
perror("fopen(output.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
int processed_count = 0;
|
||||||
|
|
||||||
|
while (iterations < 0 || processed_count < iterations) {
|
||||||
|
// Сервер блокируется на семафоре клиента (sem_wait), ожидая данных в shared memory.
|
||||||
|
if (sem_wait(g_sem_client) == -1) {
|
||||||
|
perror("sem_wait(sem_client)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!g_shm_ptr->has_data) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Warning: sem_client posted, but has_data == 0\n");
|
||||||
|
g_shm_ptr->result_code = -1;
|
||||||
|
} else {
|
||||||
|
process_line(g_shm_ptr->buffer);
|
||||||
|
|
||||||
|
g_shm_ptr->result_code = 0;
|
||||||
|
|
||||||
|
if (g_fout) {
|
||||||
|
fprintf(g_fout, "%s\n", g_shm_ptr->buffer);
|
||||||
|
fflush(g_fout);
|
||||||
|
}
|
||||||
|
|
||||||
|
g_shm_ptr->has_data = 0;
|
||||||
|
|
||||||
|
processed_count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сервер увеличивает семафор сервера (sem_post), разблокируя клиента (sem_wait).
|
||||||
|
if (sem_post(g_sem_server) == -1) {
|
||||||
|
perror("sem_post(sem_server)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_fout) {
|
||||||
|
if (fclose(g_fout) == EOF) {
|
||||||
|
perror("fclose(output.txt)");
|
||||||
|
}
|
||||||
|
g_fout = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%d\n", processed_count >= 0 ? processed_count : -1);
|
||||||
|
|
||||||
|
// Закрываем дескрипторы POSIX семафоров в процессе сервера.
|
||||||
|
if (g_sem_client) {
|
||||||
|
if (sem_close(g_sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
g_sem_client = NULL;
|
||||||
|
}
|
||||||
|
if (g_sem_server) {
|
||||||
|
if (sem_close(g_sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
g_sem_server = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sem_unlink полностью удаляет именованные семафоры из системы.
|
||||||
|
if (sem_unlink(sem_client_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_unlink(sem_server_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отсоединяем область POSIX shared memory и удаляем сам объект.
|
||||||
|
if (g_shm_ptr) {
|
||||||
|
if (munmap(g_shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
g_shm_ptr = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shm_unlink(shm_name) == -1) {
|
||||||
|
perror("shm_unlink");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
61
mine/lab_7/Makefile
Normal file
61
mine/lab_7/Makefile
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c11 -g -pthread
|
||||||
|
|
||||||
|
# Параметры по умолчанию
|
||||||
|
MAX_REPL ?= 100
|
||||||
|
INPUT1 ?= in1.txt
|
||||||
|
OUTPUT1 ?= out1.txt
|
||||||
|
INPUT2 ?= in2.txt
|
||||||
|
OUTPUT2 ?= out2.txt
|
||||||
|
|
||||||
|
all: threads_var12
|
||||||
|
|
||||||
|
threads_var12: threads_var12.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
# ===== Тесты =====
|
||||||
|
|
||||||
|
# Простой тест с одним файлом
|
||||||
|
test_one: threads_var12
|
||||||
|
@echo "=== Тест с одним файлом ==="
|
||||||
|
@echo "abacaba" > $(INPUT1)
|
||||||
|
./threads_var12 $(MAX_REPL) $(INPUT1) $(OUTPUT1)
|
||||||
|
@echo "--- input ---"
|
||||||
|
@cat $(INPUT1)
|
||||||
|
@echo "--- output ---"
|
||||||
|
@cat $(OUTPUT1)
|
||||||
|
|
||||||
|
# Тест с двумя файлами
|
||||||
|
test_two: threads_var12
|
||||||
|
@echo "=== Тест с двумя файлами ==="
|
||||||
|
@echo "abacaba" > $(INPUT1)
|
||||||
|
@echo "xxxhello" > $(INPUT2)
|
||||||
|
./threads_var12 $(MAX_REPL) $(INPUT1) $(OUTPUT1) $(INPUT2) $(OUTPUT2)
|
||||||
|
@echo "--- $(INPUT1) -> $(OUTPUT1) ---"
|
||||||
|
@cat $(INPUT1)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT1)
|
||||||
|
@echo
|
||||||
|
@echo "--- $(INPUT2) -> $(OUTPUT2) ---"
|
||||||
|
@cat $(INPUT2)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT2)
|
||||||
|
|
||||||
|
# Автотест: можно переопределять имена файлов извне
|
||||||
|
test_all: test_one test_two
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f threads_var12
|
||||||
|
rm -f in1.txt out1.txt in2.txt out2.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " all - build threads_var12"
|
||||||
|
@echo " test_one - run single-file test"
|
||||||
|
@echo " test_two - run two-file multithread test"
|
||||||
|
@echo " test_all - run all tests"
|
||||||
|
@echo " clean - remove binaries and test files"
|
||||||
|
@echo " help - show this help"
|
||||||
|
|
||||||
|
.PHONY: all test_one test_two test_all clean help
|
||||||
301
mine/lab_7/threads_var12.c
Normal file
301
mine/lab_7/threads_var12.c
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
// Многопоточная обработка файлов с использованием POSIX threads (pthread).
|
||||||
|
// Для каждого входного файла создаётся отдельный поток.
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <pthread.h> // POSIX-потоки: pthread_t, pthread_create, pthread_join, mutex
|
||||||
|
|
||||||
|
#define RBUFSZ 4096
|
||||||
|
#define WBUFSZ 4096
|
||||||
|
#define MAX_THREADS 100
|
||||||
|
|
||||||
|
// Параметры, которые главный поток передаёт в поток pthread_create.
|
||||||
|
typedef struct {
|
||||||
|
const char *input_path;
|
||||||
|
const char *output_path;
|
||||||
|
long long max_repl;
|
||||||
|
int thread_index;
|
||||||
|
int result; // Код завершения работы потока (заполняется самим потоком).
|
||||||
|
} ThreadTask;
|
||||||
|
|
||||||
|
// Глобальный мьютекс для синхронизации вывода из нескольких потоков.
|
||||||
|
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||||
|
|
||||||
|
// Выводит сообщение об ошибке, защищая вывод мьютексом (чтобы строки не перемешивались).
|
||||||
|
static void die_perror_thread(const char *what,
|
||||||
|
const char *path,
|
||||||
|
int exit_code) {
|
||||||
|
int saved = errno;
|
||||||
|
char msg[512];
|
||||||
|
|
||||||
|
if (path) {
|
||||||
|
snprintf(msg, sizeof(msg),
|
||||||
|
"%s: %s: %s\n", what, path, strerror(saved));
|
||||||
|
} else {
|
||||||
|
snprintf(msg, sizeof(msg),
|
||||||
|
"%s: %s\n", what, strerror(saved));
|
||||||
|
}
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
write(STDERR_FILENO, msg, strlen(msg));
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
(void) exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Разбор положительного long long из строки.
|
||||||
|
static long long parse_ll(const char *s) {
|
||||||
|
char *end = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long long v = strtoll(s, &end, 10);
|
||||||
|
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||||
|
errno = EINVAL;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Однопоточная обработка одного файла (фактически «тело работы» для потока).
|
||||||
|
static int process_file_variant12(const char *in_path,
|
||||||
|
const char *out_path,
|
||||||
|
long long cap) {
|
||||||
|
int in_fd = open(in_path, O_RDONLY);
|
||||||
|
if (in_fd < 0) {
|
||||||
|
die_perror_thread("open input failed", in_path, -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mode_t perms = S_IRUSR | S_IWUSR |
|
||||||
|
S_IRGRP | S_IWGRP |
|
||||||
|
S_IROTH | S_IWOTH;
|
||||||
|
|
||||||
|
int out_fd = open(out_path,
|
||||||
|
O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
|
perms);
|
||||||
|
if (out_fd < 0) {
|
||||||
|
die_perror_thread("open output failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char rbuf[RBUFSZ];
|
||||||
|
char wbuf[WBUFSZ];
|
||||||
|
size_t wlen = 0;
|
||||||
|
|
||||||
|
long long total_replacements = 0;
|
||||||
|
|
||||||
|
int at_line_start = 1;
|
||||||
|
unsigned char line_key = 0;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
||||||
|
if (n > 0) {
|
||||||
|
for (ssize_t i = 0; i < n; i++) {
|
||||||
|
unsigned char c = (unsigned char) rbuf[i];
|
||||||
|
|
||||||
|
if (at_line_start) {
|
||||||
|
line_key = c;
|
||||||
|
at_line_start = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned char outc = c;
|
||||||
|
|
||||||
|
if (c == '\n') {
|
||||||
|
at_line_start = 1;
|
||||||
|
} else if (c == line_key) {
|
||||||
|
if (total_replacements < cap) {
|
||||||
|
outc = ' ';
|
||||||
|
total_replacements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wlen == sizeof(wbuf)) {
|
||||||
|
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||||
|
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||||
|
die_perror_thread("write failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
wlen = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
wbuf[wlen++] = (char) outc;
|
||||||
|
}
|
||||||
|
} else if (n == 0) {
|
||||||
|
if (wlen > 0) {
|
||||||
|
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||||
|
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||||
|
die_perror_thread("write failed", out_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
wlen = 0;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
die_perror_thread("read failed", in_path, -1);
|
||||||
|
close(in_fd);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(in_fd) < 0) {
|
||||||
|
die_perror_thread("close input failed", in_path, -1);
|
||||||
|
close(out_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(out_fd) < 0) {
|
||||||
|
die_perror_thread("close output failed", out_path, -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Печать результата тоже защищена мьютексом, чтобы несколько потоков
|
||||||
|
// не писали одновременно в stdout и строки не «рвали» друг друга.
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
char res[64];
|
||||||
|
int m = snprintf(res, sizeof(res), "%lld\n", total_replacements);
|
||||||
|
if (m > 0) {
|
||||||
|
write(STDOUT_FILENO, res, (size_t) m);
|
||||||
|
}
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Функция, которую будет выполнять каждый поток, созданный через pthread_create.
|
||||||
|
static void *thread_func(void *arg) {
|
||||||
|
ThreadTask *task = (ThreadTask *) arg;
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
printf("[thread %d] start: %s -> %s, max_repl=%lld\n",
|
||||||
|
task->thread_index,
|
||||||
|
task->input_path,
|
||||||
|
task->output_path,
|
||||||
|
task->max_repl);
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
int rc = process_file_variant12(task->input_path,
|
||||||
|
task->output_path,
|
||||||
|
task->max_repl);
|
||||||
|
|
||||||
|
task->result = rc; // Поток записывает свой код завершения в структуру.
|
||||||
|
|
||||||
|
pthread_mutex_lock(&log_mutex);
|
||||||
|
printf("[thread %d] finished with code %d\n",
|
||||||
|
task->thread_index,
|
||||||
|
task->result);
|
||||||
|
pthread_mutex_unlock(&log_mutex);
|
||||||
|
|
||||||
|
return NULL; // Возврат из функции = завершение pthread.
|
||||||
|
}
|
||||||
|
|
||||||
|
static void print_usage(const char *progname) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <max_replacements> <input1> <output1> [<input2> <output2> ...]\n",
|
||||||
|
progname);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 100 in1.txt out1.txt in2.txt out2.txt\n",
|
||||||
|
progname);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Главный поток: создаёт потоки pthread_create, затем ждёт их завершения через pthread_join.
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4 || ((argc - 2) % 2) != 0) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Недостаточное или неверное количество аргументов\n");
|
||||||
|
print_usage(argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
long long cap = parse_ll(argv[1]);
|
||||||
|
if (cap < 0) {
|
||||||
|
die_perror_thread("invalid max_replacements", argv[1], -1);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int num_files = (argc - 2) / 2;
|
||||||
|
if (num_files > MAX_THREADS) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Слишком много файлов (максимум %d пар)\n",
|
||||||
|
MAX_THREADS);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("=== Многопоточная обработка, вариант 12 ===\n");
|
||||||
|
printf("Главный поток TID: %lu\n", (unsigned long) pthread_self());
|
||||||
|
printf("Максимум замен на файл: %lld\n", cap);
|
||||||
|
printf("Количество файловых пар: %d\n\n", num_files);
|
||||||
|
|
||||||
|
pthread_t threads[MAX_THREADS]; // Идентификаторы POSIX-потоков.
|
||||||
|
ThreadTask tasks[MAX_THREADS]; // Массив задач, по одной на поток.
|
||||||
|
|
||||||
|
// Создаём по одному потоку на каждую пару input/output.
|
||||||
|
for (int i = 0; i < num_files; i++) {
|
||||||
|
const char *input_path = argv[2 + i * 2];
|
||||||
|
const char *output_path = argv[3 + i * 2];
|
||||||
|
|
||||||
|
tasks[i].input_path = input_path;
|
||||||
|
tasks[i].output_path = output_path;
|
||||||
|
tasks[i].max_repl = cap;
|
||||||
|
tasks[i].thread_index = i + 1;
|
||||||
|
tasks[i].result = -1;
|
||||||
|
|
||||||
|
int rc = pthread_create(&threads[i],
|
||||||
|
NULL, // атрибуты по умолчанию
|
||||||
|
thread_func, // функция, с которой стартует поток
|
||||||
|
&tasks[i]); // аргумент, передаваемый функции
|
||||||
|
if (rc != 0) {
|
||||||
|
errno = rc;
|
||||||
|
die_perror_thread("pthread_create failed", NULL, -1);
|
||||||
|
tasks[i].result = -1;
|
||||||
|
threads[i] = 0; // помечаем, что поток не был создан
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int success_count = 0;
|
||||||
|
int error_count = 0;
|
||||||
|
|
||||||
|
// Ждём завершения всех созданных потоков.
|
||||||
|
for (int i = 0; i < num_files; i++) {
|
||||||
|
if (!threads[i]) {
|
||||||
|
error_count++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int rc = pthread_join(threads[i], NULL);
|
||||||
|
if (rc != 0) {
|
||||||
|
errno = rc;
|
||||||
|
die_perror_thread("pthread_join failed", NULL, -1);
|
||||||
|
error_count++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tasks[i].result == 0) {
|
||||||
|
success_count++;
|
||||||
|
} else {
|
||||||
|
error_count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("\n=== Итоговая статистика ===\n");
|
||||||
|
printf("Всего потоков: %d\n", num_files);
|
||||||
|
printf("Успешно завершено: %d\n", success_count);
|
||||||
|
printf("С ошибкой: %d\n", error_count);
|
||||||
|
|
||||||
|
if (error_count > 0) {
|
||||||
|
printf("\nОБЩИЙ СТАТУС: Завершено с ошибками\n");
|
||||||
|
return -1;
|
||||||
|
} else {
|
||||||
|
printf("\nОБЩИЙ СТАТУС: Все потоки завершены успешно\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
50
mine/lab_8/Makefile
Normal file
50
mine/lab_8/Makefile
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c11 -g
|
||||||
|
|
||||||
|
all: server_udp client_udp
|
||||||
|
|
||||||
|
server_udp: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
client_udp: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
test_server: server_udp
|
||||||
|
@echo "=== Запуск UDP-сервера ==="
|
||||||
|
@echo "Выходной файл: out.txt"
|
||||||
|
./server_udp 5000 out.txt
|
||||||
|
|
||||||
|
test_client: client_udp
|
||||||
|
@echo "=== Запуск UDP-клиента ==="
|
||||||
|
@echo "Тестовый input.txt"
|
||||||
|
@printf "abacaba\nhello\nabcaa\naaaaa\n" > input.txt
|
||||||
|
./client_udp 127.0.0.1 5000 input.txt
|
||||||
|
|
||||||
|
test_all: all
|
||||||
|
@echo "=== Автотест UDP ==="
|
||||||
|
@printf "abacaba\nhello\nabcaa\naaaaa\n" > input.txt
|
||||||
|
./server_udp 5000 out.txt & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
./client_udp 127.0.0.1 5000 input.txt; \
|
||||||
|
wait $$SRV; \
|
||||||
|
echo "--- input.txt ---"; \
|
||||||
|
cat input.txt; \
|
||||||
|
echo "--- out.txt ---"; \
|
||||||
|
cat out.txt
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f server_udp client_udp
|
||||||
|
rm -f input.txt out.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Targets:"
|
||||||
|
@echo " all - build server_udp and client_udp"
|
||||||
|
@echo " test_server - run server (port 5000, out.txt)"
|
||||||
|
@echo " test_client - run client to send input.txt"
|
||||||
|
@echo " test_all - run end-to-end UDP test"
|
||||||
|
@echo " clean - remove binaries and test files"
|
||||||
|
@echo " help - show this help"
|
||||||
|
|
||||||
|
.PHONY: all test_server test_client test_all clean help
|
||||||
125
mine/lab_8/client.c
Normal file
125
mine/lab_8/client.c
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
// UDP‑клиент: читает файл и отправляет его содержимое серверу блоками UDP.
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <arpa/inet.h> // inet_pton, sockaddr_in
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#define BUF_SIZE 4096
|
||||||
|
#define END_MARKER "END_OF_TRANSMISSION"
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// argv[1] — IP сервера, argv[2] — порт, argv[3] — входной файл.
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <server_ip> <server_port> <input_file>\n",
|
||||||
|
argv[0]);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 127.0.0.1 5000 in.txt\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *server_ip = argv[1];
|
||||||
|
const char *server_port = argv[2];
|
||||||
|
const char *input_path = argv[3];
|
||||||
|
|
||||||
|
// Разбираем номер порта.
|
||||||
|
char *endptr = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long port_long = strtol(server_port, &endptr, 10);
|
||||||
|
if (errno != 0 || endptr == server_port || *endptr != '\0' ||
|
||||||
|
port_long <= 0 || port_long > 65535) {
|
||||||
|
fprintf(stderr, "ERROR: invalid port '%s'\n", server_port);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int port = (int) port_long;
|
||||||
|
|
||||||
|
FILE *fin = fopen(input_path, "r");
|
||||||
|
if (!fin) {
|
||||||
|
perror("fopen(input_file)");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создаём UDP‑сокет.
|
||||||
|
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (sockfd < 0) {
|
||||||
|
perror("socket");
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Заполняем адрес сервера: IPv4 + порт.
|
||||||
|
struct sockaddr_in servaddr;
|
||||||
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
|
servaddr.sin_family = AF_INET;
|
||||||
|
servaddr.sin_port = htons(port);
|
||||||
|
|
||||||
|
// inet_pton конвертирует строку IP ("127.0.0.1") в бинарный вид.
|
||||||
|
if (inet_pton(AF_INET, server_ip, &servaddr.sin_addr) != 1) {
|
||||||
|
fprintf(stderr, "ERROR: invalid IP address '%s'\n", server_ip);
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char buf[BUF_SIZE];
|
||||||
|
|
||||||
|
// Читаем файл блоками и каждый блок отправляем одной UDP‑датаграммой.
|
||||||
|
for (;;) {
|
||||||
|
size_t n = fread(buf, 1, sizeof(buf), fin);
|
||||||
|
if (n > 0) {
|
||||||
|
ssize_t sent = sendto(sockfd,
|
||||||
|
buf,
|
||||||
|
n,
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &servaddr,
|
||||||
|
sizeof(servaddr));
|
||||||
|
if (sent < 0 || (size_t) sent != n) {
|
||||||
|
perror("sendto");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если прочитали меньше, чем размер буфера — это EOF или ошибка.
|
||||||
|
if (n < sizeof(buf)) {
|
||||||
|
if (ferror(fin)) {
|
||||||
|
perror("fread");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fin);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
break; // EOF.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fin) == EOF) {
|
||||||
|
perror("fclose(input_file)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем серверу маркер конца передачи.
|
||||||
|
ssize_t sent = sendto(sockfd,
|
||||||
|
END_MARKER,
|
||||||
|
strlen(END_MARKER),
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &servaddr,
|
||||||
|
sizeof(servaddr));
|
||||||
|
if (sent < 0 || (size_t) sent != strlen(END_MARKER)) {
|
||||||
|
perror("sendto(END_MARKER)");
|
||||||
|
close(sockfd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("File '%s' sent to %s:%d, END marker transmitted.\n",
|
||||||
|
input_path, server_ip, port);
|
||||||
|
|
||||||
|
close(sockfd);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
177
mine/lab_8/server.c
Normal file
177
mine/lab_8/server.c
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
// UDP‑сервер: принимает текст по сети, построчно обрабатывает и пишет в файл.
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <arpa/inet.h> // sockaddr_in, htons, htonl, ntohs, ntohl
|
||||||
|
#include <sys/socket.h> // socket, bind, recvfrom
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
|
#define BUF_SIZE 4096
|
||||||
|
#define END_MARKER "END_OF_TRANSMISSION"
|
||||||
|
|
||||||
|
// Обработка одной строки по условию: заменяет на пробелы
|
||||||
|
// все символы, совпадающие с первым, кроме самого первого.
|
||||||
|
static void process_line(char *line, long long *repl_counter) {
|
||||||
|
if (!line || !repl_counter) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t len = strlen(line);
|
||||||
|
if (len == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
char first = line[0];
|
||||||
|
|
||||||
|
for (size_t i = 1; i < len; ++i) {
|
||||||
|
if (line[i] == first && line[i] != '\n') {
|
||||||
|
line[i] = ' ';
|
||||||
|
(*repl_counter)++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// argv[1] — порт сервера UDP, argv[2] — выходной файл.
|
||||||
|
if (argc < 3) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <port> <output_file>\n",
|
||||||
|
argv[0]);
|
||||||
|
fprintf(stderr,
|
||||||
|
"Example: %s 5000 out.txt\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Разбор номера порта.
|
||||||
|
char *endptr = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long port_long = strtol(argv[1], &endptr, 10);
|
||||||
|
if (errno != 0 || endptr == argv[1] || *endptr != '\0' ||
|
||||||
|
port_long <= 0 || port_long > 65535) {
|
||||||
|
fprintf(stderr, "ERROR: invalid port '%s'\n", argv[1]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int port = (int) port_long;
|
||||||
|
|
||||||
|
const char *out_path = argv[2];
|
||||||
|
|
||||||
|
FILE *fout = fopen(out_path, "w");
|
||||||
|
if (!fout) {
|
||||||
|
perror("fopen(output_file)");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создаём UDP‑сокет: AF_INET (IPv4), SOCK_DGRAM (UDP).
|
||||||
|
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
|
if (sockfd < 0) {
|
||||||
|
perror("socket");
|
||||||
|
fclose(fout);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Заполняем адрес сервера и привязываем сокет к порту (bind).
|
||||||
|
struct sockaddr_in servaddr;
|
||||||
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
|
servaddr.sin_family = AF_INET; // IPv4.
|
||||||
|
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // принимать на всех интерфейсах.
|
||||||
|
servaddr.sin_port = htons(port); // порт в сетевом порядке байт.
|
||||||
|
|
||||||
|
if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
|
||||||
|
perror("bind");
|
||||||
|
close(sockfd);
|
||||||
|
fclose(fout);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("UDP server is listening on port %d, output file: %s\n",
|
||||||
|
port, out_path);
|
||||||
|
|
||||||
|
char buf[BUF_SIZE]; // сюда прилетают UDP‑датаграммы.
|
||||||
|
char line_buf[BUF_SIZE]; // здесь накапливаем одну логическую строку.
|
||||||
|
size_t line_len = 0;
|
||||||
|
long long total_replacements = 0;
|
||||||
|
|
||||||
|
int done = 0; // флаг завершения по END_MARKER.
|
||||||
|
|
||||||
|
while (!done) {
|
||||||
|
struct sockaddr_in cliaddr;
|
||||||
|
socklen_t cli_len = sizeof(cliaddr);
|
||||||
|
|
||||||
|
// recvfrom читает один UDP‑пакет и заполняет адрес отправителя.
|
||||||
|
ssize_t n = recvfrom(sockfd,
|
||||||
|
buf,
|
||||||
|
sizeof(buf) - 1,
|
||||||
|
0,
|
||||||
|
(struct sockaddr *) &cliaddr,
|
||||||
|
&cli_len);
|
||||||
|
if (n < 0) {
|
||||||
|
perror("recvfrom");
|
||||||
|
total_replacements = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
buf[n] = '\0'; // удобнее работать как со строкой.
|
||||||
|
|
||||||
|
// Специальный маркер конца передачи от клиента.
|
||||||
|
if (strcmp(buf, END_MARKER) == 0) {
|
||||||
|
printf("Received END marker, finishing.\n");
|
||||||
|
done = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Разбор принятого блока посимвольно, сборка полных строк по '\n'.
|
||||||
|
size_t pos = 0;
|
||||||
|
while (pos < (size_t) n) {
|
||||||
|
char c = buf[pos++];
|
||||||
|
if (c == '\n') {
|
||||||
|
// Закончили строку в line_buf.
|
||||||
|
line_buf[line_len] = '\0';
|
||||||
|
process_line(line_buf, &total_replacements);
|
||||||
|
if (fprintf(fout, "%s\n", line_buf) < 0) {
|
||||||
|
perror("fprintf");
|
||||||
|
total_replacements = -1;
|
||||||
|
done = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
line_len = 0;
|
||||||
|
} else {
|
||||||
|
// Продолжаем накапливать строку.
|
||||||
|
if (line_len + 1 < sizeof(line_buf)) {
|
||||||
|
line_buf[line_len++] = c;
|
||||||
|
} else {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Line buffer overflow, truncating line\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если соединение завершилось не на границе строки —
|
||||||
|
// доробатываем последний неполный хвост в line_buf.
|
||||||
|
if (line_len > 0 && total_replacements >= 0) {
|
||||||
|
line_buf[line_len] = '\0';
|
||||||
|
process_line(line_buf, &total_replacements);
|
||||||
|
if (fprintf(fout, "%s\n", line_buf) < 0) {
|
||||||
|
perror("fprintf");
|
||||||
|
total_replacements = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fout) == EOF) {
|
||||||
|
perror("fclose(output_file)");
|
||||||
|
total_replacements = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
close(sockfd);
|
||||||
|
|
||||||
|
printf("Total replacements: %lld\n", total_replacements);
|
||||||
|
if (total_replacements < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
20
mine/rgz/Makefile
Normal file
20
mine/rgz/Makefile
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -O2
|
||||||
|
LDFLAGS =
|
||||||
|
|
||||||
|
all: daemon client
|
||||||
|
|
||||||
|
daemon: fifo_server_daemon.o
|
||||||
|
$(CC) $(CFLAGS) -o fifo_server_daemon fifo_server_daemon.o $(LDFLAGS)
|
||||||
|
|
||||||
|
client: fifo_client.o
|
||||||
|
$(CC) $(CFLAGS) -o fifo_client fifo_client.o $(LDFLAGS)
|
||||||
|
|
||||||
|
fifo_server_daemon.o: fifo_server_daemon.c
|
||||||
|
$(CC) $(CFLAGS) -c fifo_server_daemon.c
|
||||||
|
|
||||||
|
fifo_client.o: fifo_client.c
|
||||||
|
$(CC) $(CFLAGS) -c fifo_client.c
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -f fifo_server_daemon fifo_client *.o
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
// fifo_client.c - Клиентская программа с использованием именованных каналов (FIFO)
|
// fifo_client.c
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
@@ -33,7 +32,6 @@ int main(int argc, char *argv[]) {
|
|||||||
printf("Входной файл: %s\n", input_file);
|
printf("Входной файл: %s\n", input_file);
|
||||||
printf("Выходной файл: %s\n", output_file);
|
printf("Выходной файл: %s\n", output_file);
|
||||||
|
|
||||||
// Открываем входной файл
|
|
||||||
int in_fd = open(input_file, O_RDONLY);
|
int in_fd = open(input_file, O_RDONLY);
|
||||||
if (in_fd < 0) {
|
if (in_fd < 0) {
|
||||||
fprintf(stderr, "ERROR: Не удалось открыть входной файл %s: %s\n",
|
fprintf(stderr, "ERROR: Не удалось открыть входной файл %s: %s\n",
|
||||||
@@ -41,7 +39,6 @@ int main(int argc, char *argv[]) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Читаем данные из файла
|
|
||||||
char *buffer = malloc(BUFFER_SIZE);
|
char *buffer = malloc(BUFFER_SIZE);
|
||||||
if (!buffer) {
|
if (!buffer) {
|
||||||
fprintf(stderr, "ERROR: Не удалось выделить память\n");
|
fprintf(stderr, "ERROR: Не удалось выделить память\n");
|
||||||
@@ -51,7 +48,6 @@ int main(int argc, char *argv[]) {
|
|||||||
|
|
||||||
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE - 1);
|
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE - 1);
|
||||||
close(in_fd);
|
close(in_fd);
|
||||||
|
|
||||||
if (bytes_read < 0) {
|
if (bytes_read < 0) {
|
||||||
fprintf(stderr, "ERROR: Не удалось прочитать файл: %s\n", strerror(errno));
|
fprintf(stderr, "ERROR: Не удалось прочитать файл: %s\n", strerror(errno));
|
||||||
free(buffer);
|
free(buffer);
|
||||||
@@ -61,20 +57,17 @@ int main(int argc, char *argv[]) {
|
|||||||
buffer[bytes_read] = '\0';
|
buffer[bytes_read] = '\0';
|
||||||
printf("Прочитано байт из файла: %zd\n", bytes_read);
|
printf("Прочитано байт из файла: %zd\n", bytes_read);
|
||||||
|
|
||||||
// Открываем FIFO для отправки запроса
|
|
||||||
printf("Отправка запроса серверу...\n");
|
printf("Отправка запроса серверу...\n");
|
||||||
int fd_req = open(FIFO_REQUEST, O_WRONLY);
|
int fd_req = open(FIFO_REQUEST, O_WRONLY);
|
||||||
if (fd_req == -1) {
|
if (fd_req == -1) {
|
||||||
fprintf(stderr, "ERROR: Не удалось открыть FIFO запроса: %s\n", strerror(errno));
|
fprintf(stderr, "ERROR: Не удалось открыть FIFO запроса: %s\n", strerror(errno));
|
||||||
fprintf(stderr, "Убедитесь, что сервер запущен!\n");
|
fprintf(stderr, "Убедитесь, что сервер (демон) запущен!\n");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Отправляем данные серверу
|
|
||||||
ssize_t bytes_written = write(fd_req, buffer, bytes_read);
|
ssize_t bytes_written = write(fd_req, buffer, bytes_read);
|
||||||
close(fd_req);
|
close(fd_req);
|
||||||
|
|
||||||
if (bytes_written != bytes_read) {
|
if (bytes_written != bytes_read) {
|
||||||
fprintf(stderr, "ERROR: Ошибка отправки данных\n");
|
fprintf(stderr, "ERROR: Ошибка отправки данных\n");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
@@ -83,7 +76,6 @@ int main(int argc, char *argv[]) {
|
|||||||
|
|
||||||
printf("Отправлено байт: %zd\n", bytes_written);
|
printf("Отправлено байт: %zd\n", bytes_written);
|
||||||
|
|
||||||
// Открываем FIFO для получения ответа
|
|
||||||
printf("Ожидание ответа от сервера...\n");
|
printf("Ожидание ответа от сервера...\n");
|
||||||
int fd_resp = open(FIFO_RESPONSE, O_RDONLY);
|
int fd_resp = open(FIFO_RESPONSE, O_RDONLY);
|
||||||
if (fd_resp == -1) {
|
if (fd_resp == -1) {
|
||||||
@@ -92,10 +84,8 @@ int main(int argc, char *argv[]) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Читаем обработанные данные
|
|
||||||
ssize_t response_bytes = read(fd_resp, buffer, BUFFER_SIZE - 1);
|
ssize_t response_bytes = read(fd_resp, buffer, BUFFER_SIZE - 1);
|
||||||
close(fd_resp);
|
close(fd_resp);
|
||||||
|
|
||||||
if (response_bytes < 0) {
|
if (response_bytes < 0) {
|
||||||
fprintf(stderr, "ERROR: Ошибка чтения ответа\n");
|
fprintf(stderr, "ERROR: Ошибка чтения ответа\n");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
@@ -105,17 +95,14 @@ int main(int argc, char *argv[]) {
|
|||||||
buffer[response_bytes] = '\0';
|
buffer[response_bytes] = '\0';
|
||||||
printf("Получено байт от сервера: %zd\n", response_bytes);
|
printf("Получено байт от сервера: %zd\n", response_bytes);
|
||||||
|
|
||||||
// Ищем информацию о количестве замен
|
|
||||||
char *replacements_info = strstr(buffer, "\nREPLACEMENTS:");
|
char *replacements_info = strstr(buffer, "\nREPLACEMENTS:");
|
||||||
long long replacements = 0;
|
long long replacements = 0;
|
||||||
|
|
||||||
if (replacements_info) {
|
if (replacements_info) {
|
||||||
sscanf(replacements_info, "\nREPLACEMENTS:%lld", &replacements);
|
sscanf(replacements_info, "\nREPLACEMENTS:%lld", &replacements);
|
||||||
*replacements_info = '\0'; // Обрезаем служебную информацию
|
*replacements_info = '\0';
|
||||||
response_bytes = replacements_info - buffer;
|
response_bytes = replacements_info - buffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Открываем выходной файл
|
|
||||||
int out_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC,
|
int out_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
|
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
|
||||||
if (out_fd < 0) {
|
if (out_fd < 0) {
|
||||||
@@ -125,10 +112,8 @@ int main(int argc, char *argv[]) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Записываем обработанные данные
|
|
||||||
ssize_t written = write(out_fd, buffer, response_bytes);
|
ssize_t written = write(out_fd, buffer, response_bytes);
|
||||||
close(out_fd);
|
close(out_fd);
|
||||||
|
|
||||||
if (written != response_bytes) {
|
if (written != response_bytes) {
|
||||||
fprintf(stderr, "ERROR: Ошибка записи в выходной файл\n");
|
fprintf(stderr, "ERROR: Ошибка записи в выходной файл\n");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
191
mine/rgz/fifo_server_daemon.c
Normal file
191
mine/rgz/fifo_server_daemon.c
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
// fifo_server_daemon.c
|
||||||
|
#include <stdio.h> // fprintf (для ошибок до старта)
|
||||||
|
#include <stdlib.h> // malloc, free, exit, strtoll
|
||||||
|
#include <string.h> // strlen, strerror
|
||||||
|
#include <unistd.h> // read, write, close, unlink
|
||||||
|
#include <fcntl.h> // open, O_RDONLY, O_WRONLY
|
||||||
|
#include <sys/types.h> // типы для системных вызовов
|
||||||
|
#include <sys/stat.h> // mkfifo, права доступа, umask
|
||||||
|
#include <errno.h> // errno
|
||||||
|
#include <signal.h> // signal, SIGINT, SIGTERM, SIGPIPE
|
||||||
|
#include <syslog.h> // syslog, openlog, closelog
|
||||||
|
|
||||||
|
#define FIFO_REQUEST "/tmp/fifo_request"
|
||||||
|
#define FIFO_RESPONSE "/tmp/fifo_response"
|
||||||
|
#define BUFFER_SIZE 4096
|
||||||
|
|
||||||
|
volatile sig_atomic_t running = 1;
|
||||||
|
|
||||||
|
void signal_handler(int sig) {
|
||||||
|
(void)sig;
|
||||||
|
syslog(LOG_INFO, "Signal %d received, stopping...", sig);
|
||||||
|
running = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// разбор неотрицательного long long
|
||||||
|
static long long parse_ll(const char *s) {
|
||||||
|
char *end = NULL;
|
||||||
|
errno = 0;
|
||||||
|
long long v = strtoll(s, &end, 10);
|
||||||
|
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// логика обработки текста (как в исходном сервере)
|
||||||
|
long long process_data(const char *input, size_t input_len,
|
||||||
|
char *output, size_t output_size,
|
||||||
|
long long max_replacements) {
|
||||||
|
long long total_replacements = 0;
|
||||||
|
int at_line_start = 1;
|
||||||
|
unsigned char line_key = 0;
|
||||||
|
size_t out_pos = 0;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < input_len && out_pos < output_size - 1; i++) {
|
||||||
|
unsigned char c = (unsigned char)input[i];
|
||||||
|
|
||||||
|
if (at_line_start) {
|
||||||
|
line_key = c;
|
||||||
|
at_line_start = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned char outc = c;
|
||||||
|
|
||||||
|
if (c == '\n') {
|
||||||
|
at_line_start = 1;
|
||||||
|
} else if (c == line_key && total_replacements < max_replacements) {
|
||||||
|
outc = ' ';
|
||||||
|
total_replacements++;
|
||||||
|
}
|
||||||
|
|
||||||
|
output[out_pos++] = (char)outc;
|
||||||
|
}
|
||||||
|
|
||||||
|
output[out_pos] = '\0';
|
||||||
|
return total_replacements;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc != 2) {
|
||||||
|
fprintf(stderr, "Usage: %s <max_replacements>\n", argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
long long max_replacements = parse_ll(argv[1]);
|
||||||
|
if (max_replacements < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Invalid max_replacements\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* работаем в foreground, демонизацию делает systemd (Type=simple) */
|
||||||
|
|
||||||
|
openlog("fifo_server_daemon", LOG_PID | LOG_NDELAY, LOG_DAEMON);
|
||||||
|
syslog(LOG_INFO, "Server started (systemd), max_replacements=%lld",
|
||||||
|
max_replacements);
|
||||||
|
|
||||||
|
signal(SIGINT, signal_handler);
|
||||||
|
signal(SIGTERM, signal_handler);
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
|
||||||
|
unlink(FIFO_REQUEST);
|
||||||
|
unlink(FIFO_RESPONSE);
|
||||||
|
|
||||||
|
if (mkfifo(FIFO_REQUEST, 0666) == -1) {
|
||||||
|
syslog(LOG_ERR, "mkfifo request failed: %s", strerror(errno));
|
||||||
|
closelog();
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mkfifo(FIFO_RESPONSE, 0666) == -1) {
|
||||||
|
syslog(LOG_ERR, "mkfifo response failed: %s", strerror(errno));
|
||||||
|
unlink(FIFO_REQUEST);
|
||||||
|
closelog();
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
syslog(LOG_INFO, "FIFO created: request=%s, response=%s",
|
||||||
|
FIFO_REQUEST, FIFO_RESPONSE);
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
int fd_req = open(FIFO_REQUEST, O_RDONLY);
|
||||||
|
if (!running) { // сигнал пришёл во время open
|
||||||
|
if (fd_req != -1)
|
||||||
|
close(fd_req);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (fd_req == -1) {
|
||||||
|
if (errno == EINTR)
|
||||||
|
continue;
|
||||||
|
syslog(LOG_ERR, "open request FIFO failed: %s", strerror(errno));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *input_buffer = malloc(BUFFER_SIZE);
|
||||||
|
char *output_buffer = malloc(BUFFER_SIZE);
|
||||||
|
if (!input_buffer || !output_buffer) {
|
||||||
|
syslog(LOG_ERR, "Memory allocation failed");
|
||||||
|
close(fd_req);
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
break; // выходим, не крутимся дальше
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t bytes_read = read(fd_req, input_buffer, BUFFER_SIZE - 1);
|
||||||
|
close(fd_req);
|
||||||
|
|
||||||
|
if (!running) { // сигнал во время read
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytes_read <= 0) {
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
if (!running)
|
||||||
|
break;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
input_buffer[bytes_read] = '\0';
|
||||||
|
syslog(LOG_INFO, "Request received: %zd bytes", bytes_read);
|
||||||
|
|
||||||
|
long long replacements =
|
||||||
|
process_data(input_buffer, (size_t)bytes_read,
|
||||||
|
output_buffer, BUFFER_SIZE,
|
||||||
|
max_replacements);
|
||||||
|
|
||||||
|
syslog(LOG_INFO, "Replacements done: %lld", replacements);
|
||||||
|
|
||||||
|
int fd_resp = open(FIFO_RESPONSE, O_WRONLY);
|
||||||
|
if (fd_resp == -1) {
|
||||||
|
syslog(LOG_ERR, "open response FIFO failed: %s", strerror(errno));
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
if (!running)
|
||||||
|
break;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t output_len = strlen(output_buffer);
|
||||||
|
ssize_t bytes_written = write(fd_resp, output_buffer, output_len);
|
||||||
|
|
||||||
|
char result[64];
|
||||||
|
snprintf(result, sizeof(result), "\nREPLACEMENTS:%lld\n", replacements);
|
||||||
|
write(fd_resp, result, strlen(result));
|
||||||
|
|
||||||
|
close(fd_resp);
|
||||||
|
|
||||||
|
syslog(LOG_INFO, "Response sent: %zd bytes", bytes_written);
|
||||||
|
|
||||||
|
free(input_buffer);
|
||||||
|
free(output_buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
syslog(LOG_INFO, "Server stopping, cleaning up");
|
||||||
|
unlink(FIFO_REQUEST);
|
||||||
|
unlink(FIFO_RESPONSE);
|
||||||
|
closelog();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
4
mine/rgz/input.txt
Normal file
4
mine/rgz/input.txt
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
abacaba
|
||||||
|
hello
|
||||||
|
abcaa
|
||||||
|
aaaaa
|
||||||
37
mine/rgz/service.sh
Executable file
37
mine/rgz/service.sh
Executable file
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
target=/etc/systemd/system/fifo_server_daemon.service
|
||||||
|
|
||||||
|
tmp=$(mktemp)
|
||||||
|
trap 'rm -f "$tmp"' EXIT
|
||||||
|
|
||||||
|
cat > "$tmp" <<'UNIT'
|
||||||
|
[Unit]
|
||||||
|
Description=FIFO text processing daemon (systemd-managed)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/home/pajjilykk/CLionProjects/CS-LABS/mine/rgz/fifo_server_daemon 1000
|
||||||
|
User=pajjilykk
|
||||||
|
Group=pajjilykk
|
||||||
|
WorkingDirectory=/home/pajjilykk/CLionProjects/CS-LABS/mine/rgz
|
||||||
|
|
||||||
|
# мягко останавливать и давать время на выход
|
||||||
|
KillSignal=SIGTERM
|
||||||
|
TimeoutStopSec=5s
|
||||||
|
KillMode=control-group
|
||||||
|
|
||||||
|
# перезапускать при падении/timeout
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=1s
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
UNIT
|
||||||
|
|
||||||
|
sudo install -m 0644 "$tmp" "$target"
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
|
||||||
|
echo "Replaced \`$target\` with the predefined service unit."
|
||||||
61
vlad/lab_5/Makefile
Normal file
61
vlad/lab_5/Makefile
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_MQ = -lrt # POSIX message queues on Linux
|
||||||
|
|
||||||
|
TEST_INPUT = test_input.txt
|
||||||
|
TEST_OUTPUT = test_output.txt
|
||||||
|
|
||||||
|
all: msg
|
||||||
|
|
||||||
|
# ===== POSIX MQ targets =====
|
||||||
|
msg: mq_server mq_client
|
||||||
|
|
||||||
|
mq_server: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
mq_client: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_MQ)
|
||||||
|
|
||||||
|
# ===== Ручные тесты =====
|
||||||
|
|
||||||
|
test_server: msg
|
||||||
|
@echo "=== Запуск MQ сервера ==="
|
||||||
|
@echo "В другом терминале выполните: make test_client_manual"
|
||||||
|
./mq_server
|
||||||
|
|
||||||
|
test_client_manual: msg
|
||||||
|
@echo "=== Запуск MQ клиента (ручной тест) ==="
|
||||||
|
./mq_client $(TEST_INPUT) $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
# ===== Автотест: сервер в фоне + клиент =====
|
||||||
|
|
||||||
|
test_all: msg
|
||||||
|
@echo "=== Автотест MQ (server + client) ==="
|
||||||
|
@echo "Создание тестового входного файла..."
|
||||||
|
echo "aabbccddeeff" > $(TEST_INPUT)
|
||||||
|
@echo "Старт сервера в фоне..."
|
||||||
|
./mq_server & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
echo "Запуск клиента..."; \
|
||||||
|
./mq_client $(TEST_INPUT) $(TEST_OUTPUT); \
|
||||||
|
echo "Остановка сервера..."; \
|
||||||
|
kill $$SRV || true; \
|
||||||
|
wait $$SRV 2>/dev/null || true; \
|
||||||
|
echo "=== Содержимое $(TEST_OUTPUT) ==="; \
|
||||||
|
cat $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f mq_server mq_client *.o $(TEST_INPUT) $(TEST_OUTPUT)
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " msg - Build POSIX MQ programs"
|
||||||
|
@echo " test_server - Run MQ server (client separately)"
|
||||||
|
@echo " test_client_manual- Run client (server must be running)"
|
||||||
|
@echo " test_all - Automatic end-to-end test (server+client)"
|
||||||
|
@echo " clean - Remove built and test files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all msg test_server test_client_manual test_all clean help
|
||||||
160
vlad/lab_5/client.c
Normal file
160
vlad/lab_5/client.c
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
// client.c (mq_client.c)
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <errno.h>
|
||||||
|
|
||||||
|
#include <mqueue.h>
|
||||||
|
|
||||||
|
#define MQ_REQUEST "/mq_request"
|
||||||
|
#define MQ_RESPONSE "/mq_response"
|
||||||
|
#define MQ_MAXMSG 10
|
||||||
|
#define BUFFER_SIZE 4096
|
||||||
|
|
||||||
|
void print_usage(const char *progname) {
|
||||||
|
fprintf(stderr, "Usage: %s <input_file> <output_file>\n", progname);
|
||||||
|
fprintf(stderr, "Example: %s input.txt output.txt\n", progname);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc != 3) {
|
||||||
|
fprintf(stderr, "ERROR: Неверное количество аргументов\n");
|
||||||
|
print_usage(argv[0]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *input_file = argv[1];
|
||||||
|
const char *output_file = argv[2];
|
||||||
|
|
||||||
|
printf("=== MQ Client ===\n");
|
||||||
|
printf("Input file : %s\n", input_file);
|
||||||
|
printf("Output file: %s\n", output_file);
|
||||||
|
|
||||||
|
int in_fd = open(input_file, O_RDONLY);
|
||||||
|
if (in_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть входной файл %s: %s\n",
|
||||||
|
input_file, strerror(errno));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *buffer = malloc(BUFFER_SIZE);
|
||||||
|
if (!buffer) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось выделить память\n");
|
||||||
|
close(in_fd);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE - 1);
|
||||||
|
close(in_fd);
|
||||||
|
if (bytes_read < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось прочитать файл: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer[bytes_read] = '\0';
|
||||||
|
printf("Прочитано байт из файла: %zd\n", bytes_read);
|
||||||
|
|
||||||
|
struct mq_attr attr;
|
||||||
|
memset(&attr, 0, sizeof(attr));
|
||||||
|
attr.mq_flags = 0;
|
||||||
|
attr.mq_maxmsg = MQ_MAXMSG;
|
||||||
|
attr.mq_msgsize = BUFFER_SIZE;
|
||||||
|
attr.mq_curmsgs = 0;
|
||||||
|
|
||||||
|
mqd_t mq_req = mq_open(MQ_REQUEST, O_WRONLY);
|
||||||
|
if (mq_req == (mqd_t)-1) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Не удалось открыть очередь запросов %s: %s\n",
|
||||||
|
MQ_REQUEST, strerror(errno));
|
||||||
|
fprintf(stderr, "Убедитесь, что сервер запущен!\n");
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mqd_t mq_resp = mq_open(MQ_RESPONSE, O_RDONLY);
|
||||||
|
if (mq_resp == (mqd_t)-1) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"ERROR: Не удалось открыть очередь ответов %s: %s\n",
|
||||||
|
MQ_RESPONSE, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mq_send(mq_req, buffer, (size_t)bytes_read, 0) == -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_send failed: %s\n", strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Отправлено байт: %zd\n", bytes_read);
|
||||||
|
|
||||||
|
// ВАЖНО: размер буфера для mq_receive >= mq_msgsize
|
||||||
|
ssize_t resp_bytes = mq_receive(mq_resp, buffer, BUFFER_SIZE, NULL);
|
||||||
|
if (resp_bytes < 0) {
|
||||||
|
fprintf(stderr, "ERROR: mq_receive failed: %s\n", strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resp_bytes >= BUFFER_SIZE)
|
||||||
|
resp_bytes = BUFFER_SIZE - 1;
|
||||||
|
buffer[resp_bytes] = '\0';
|
||||||
|
|
||||||
|
printf("Получено байт от сервера: %zd\n", resp_bytes);
|
||||||
|
|
||||||
|
char *repl_info = strstr(buffer, "\nREPLACEMENTS:");
|
||||||
|
long long replacements = 0;
|
||||||
|
|
||||||
|
if (repl_info) {
|
||||||
|
sscanf(repl_info, "\nREPLACEMENTS:%lld", &replacements);
|
||||||
|
*repl_info = '\0';
|
||||||
|
resp_bytes = repl_info - buffer;
|
||||||
|
} else {
|
||||||
|
fprintf(stderr,
|
||||||
|
"WARNING: Не найдена служебная строка REPLACEMENTS, "
|
||||||
|
"запишем весь ответ как есть\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
int out_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC,
|
||||||
|
S_IRUSR | S_IWUSR |
|
||||||
|
S_IRGRP | S_IWGRP |
|
||||||
|
S_IROTH | S_IWOTH);
|
||||||
|
if (out_fd < 0) {
|
||||||
|
fprintf(stderr, "ERROR: Не удалось открыть выходной файл %s: %s\n",
|
||||||
|
output_file, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize_t written = write(out_fd, buffer, resp_bytes);
|
||||||
|
close(out_fd);
|
||||||
|
if (written != resp_bytes) {
|
||||||
|
fprintf(stderr, "ERROR: Ошибка записи в выходной файл\n");
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Записано байт в выходной файл: %zd\n", written);
|
||||||
|
printf("Количество выполненных замен: %lld\n", replacements);
|
||||||
|
printf("\nОбработка завершена успешно!\n");
|
||||||
|
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
free(buffer);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
157
vlad/lab_5/server.c
Normal file
157
vlad/lab_5/server.c
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
// mq_server.c
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <signal.h>
|
||||||
|
|
||||||
|
#include <mqueue.h> // POSIX message queues
|
||||||
|
|
||||||
|
#define MQ_REQUEST "/mq_request"
|
||||||
|
#define MQ_RESPONSE "/mq_response"
|
||||||
|
#define MQ_MAXMSG 10
|
||||||
|
#define BUFFER_SIZE 4096 // msgsize очереди и размер буферов
|
||||||
|
|
||||||
|
volatile sig_atomic_t running = 1;
|
||||||
|
|
||||||
|
void signal_handler(int sig) {
|
||||||
|
(void)sig;
|
||||||
|
running = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// во всех парах одинаковых подряд символов второй -> пробел
|
||||||
|
long long process_text(const char *input, size_t len,
|
||||||
|
char *output, size_t out_size) {
|
||||||
|
if (out_size == 0) return -1;
|
||||||
|
|
||||||
|
long long replacements = 0;
|
||||||
|
size_t out_pos = 0;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < len && out_pos < out_size - 1; i++) {
|
||||||
|
char c = input[i];
|
||||||
|
output[out_pos++] = c;
|
||||||
|
|
||||||
|
if (i + 1 < len && input[i] == input[i + 1]) {
|
||||||
|
// вторая буква пары
|
||||||
|
if (out_pos < out_size - 1) {
|
||||||
|
output[out_pos++] = ' ';
|
||||||
|
replacements++;
|
||||||
|
}
|
||||||
|
i++; // пропускаем второй символ исходного текста
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output[out_pos] = '\0';
|
||||||
|
return replacements;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
struct mq_attr attr;
|
||||||
|
mqd_t mq_req = (mqd_t)-1;
|
||||||
|
mqd_t mq_resp = (mqd_t)-1;
|
||||||
|
|
||||||
|
memset(&attr, 0, sizeof(attr));
|
||||||
|
attr.mq_flags = 0;
|
||||||
|
attr.mq_maxmsg = MQ_MAXMSG;
|
||||||
|
attr.mq_msgsize = BUFFER_SIZE;
|
||||||
|
attr.mq_curmsgs = 0;
|
||||||
|
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
mq_unlink(MQ_RESPONSE);
|
||||||
|
|
||||||
|
mq_req = mq_open(MQ_REQUEST, O_CREAT | O_RDONLY, 0666, &attr);
|
||||||
|
if (mq_req == (mqd_t)-1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_open(%s) failed: %s\n",
|
||||||
|
MQ_REQUEST, strerror(errno));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mq_resp = mq_open(MQ_RESPONSE, O_CREAT | O_WRONLY, 0666, &attr);
|
||||||
|
if (mq_resp == (mqd_t)-1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_open(%s) failed: %s\n",
|
||||||
|
MQ_RESPONSE, strerror(errno));
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("=== MQ Server started ===\n");
|
||||||
|
printf("Request queue : %s\n", MQ_REQUEST);
|
||||||
|
printf("Response queue: %s\n", MQ_RESPONSE);
|
||||||
|
|
||||||
|
signal(SIGINT, signal_handler);
|
||||||
|
signal(SIGTERM, signal_handler);
|
||||||
|
|
||||||
|
char in_buf[BUFFER_SIZE];
|
||||||
|
char out_buf[BUFFER_SIZE];
|
||||||
|
|
||||||
|
while (running) {
|
||||||
|
unsigned int prio = 0;
|
||||||
|
ssize_t bytes_read = mq_receive(mq_req, in_buf,
|
||||||
|
sizeof(in_buf), &prio);
|
||||||
|
if (bytes_read < 0) {
|
||||||
|
if (errno == EINTR && !running)
|
||||||
|
break;
|
||||||
|
if (errno == EINTR)
|
||||||
|
continue;
|
||||||
|
fprintf(stderr, "ERROR: mq_receive failed: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytes_read >= (ssize_t)sizeof(in_buf))
|
||||||
|
bytes_read = sizeof(in_buf) - 1;
|
||||||
|
in_buf[bytes_read] = '\0';
|
||||||
|
printf("Received request: %zd bytes\n", bytes_read);
|
||||||
|
|
||||||
|
long long repl = process_text(in_buf, (size_t)bytes_read,
|
||||||
|
out_buf, sizeof(out_buf));
|
||||||
|
if (repl < 0) {
|
||||||
|
const char *err_msg = "ERROR: processing failed\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Replacements done: %lld\n", repl);
|
||||||
|
|
||||||
|
char resp_buf[BUFFER_SIZE];
|
||||||
|
size_t processed_len = strlen(out_buf);
|
||||||
|
|
||||||
|
if (processed_len + 64 >= sizeof(resp_buf)) {
|
||||||
|
const char *err_msg = "ERROR: response too long\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(resp_buf, out_buf, processed_len);
|
||||||
|
int n = snprintf(resp_buf + processed_len,
|
||||||
|
sizeof(resp_buf) - processed_len,
|
||||||
|
"\nREPLACEMENTS:%lld\n", repl);
|
||||||
|
if (n < 0) {
|
||||||
|
const char *err_msg = "ERROR: snprintf failed\n";
|
||||||
|
mq_send(mq_resp, err_msg, strlen(err_msg), 0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t resp_len = processed_len + (size_t)n;
|
||||||
|
|
||||||
|
if (mq_send(mq_resp, resp_buf, resp_len, 0) == -1) {
|
||||||
|
fprintf(stderr, "ERROR: mq_send failed: %s\n",
|
||||||
|
strerror(errno));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Response sent: %zu bytes\n\n", resp_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Server shutting down...\n");
|
||||||
|
mq_close(mq_req);
|
||||||
|
mq_close(mq_resp);
|
||||||
|
mq_unlink(MQ_REQUEST);
|
||||||
|
mq_unlink(MQ_RESPONSE);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
51
vlad/lab_6/Makefile
Normal file
51
vlad/lab_6/Makefile
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||||
|
LDFLAGS_IPC = -lrt -pthread
|
||||||
|
|
||||||
|
SHM_NAME ?= /myshm
|
||||||
|
SEM_CLIENT_NAME ?= /sem_client
|
||||||
|
SEM_SERVER_NAME ?= /sem_server
|
||||||
|
SERVER_ITERS ?= 1000
|
||||||
|
|
||||||
|
all: shm
|
||||||
|
|
||||||
|
shm: server client
|
||||||
|
|
||||||
|
server: server.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
|
||||||
|
|
||||||
|
client: client.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
|
||||||
|
|
||||||
|
test_server: shm
|
||||||
|
@echo "=== Запуск сервера POSIX SHM+SEM ==="
|
||||||
|
@echo "В другом терминале выполните: make test_client"
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS)
|
||||||
|
|
||||||
|
test_client: shm
|
||||||
|
@echo "=== Запуск клиента, чтение input.txt, вывод на stdout ==="
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME)
|
||||||
|
|
||||||
|
test_all: shm
|
||||||
|
@echo "=== Автотест POSIX SHM+SEM с файлами input.txt/output.txt ==="
|
||||||
|
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS) & \
|
||||||
|
SRV=$$!; \
|
||||||
|
sleep 1; \
|
||||||
|
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME); \
|
||||||
|
wait $$SRV
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f server client
|
||||||
|
rm -f output.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " shm - Build POSIX SHM+SEM programs"
|
||||||
|
@echo " test_server - Run SHM+SEM server (client in another terminal)"
|
||||||
|
@echo " test_client - Run client reading input.txt"
|
||||||
|
@echo " test_all - Automatic end-to-end test with input.txt/output.txt"
|
||||||
|
@echo " clean - Remove built files"
|
||||||
|
@echo " help - Show this help"
|
||||||
|
|
||||||
|
.PHONY: all shm test_server test_client test_all clean help
|
||||||
147
vlad/lab_6/client.c
Normal file
147
vlad/lab_6/client.c
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
// client.c
|
||||||
|
// Клиент: читает строки из input.txt, передаёт их серверу через shared memory,
|
||||||
|
// ожидает обработку и печатает результат на stdout. [file:21][file:22]
|
||||||
|
|
||||||
|
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fgets
|
||||||
|
#include <stdlib.h> // exit, EXIT_FAILURE
|
||||||
|
#include <string.h> // memset, strncpy, strlen
|
||||||
|
#include <errno.h> // errno
|
||||||
|
#include <fcntl.h> // O_RDWR
|
||||||
|
#include <sys/mman.h> // shm_open, mmap, munmap
|
||||||
|
#include <sys/stat.h> // mode_t
|
||||||
|
#include <semaphore.h> // sem_t, sem_open, sem_close, sem_wait, sem_post
|
||||||
|
#include <unistd.h> // close
|
||||||
|
|
||||||
|
#define SHM_BUFFER_SIZE 1024 // Должен совпадать с server.c. [file:21]
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int has_data; // Флаг наличия данных. [file:21]
|
||||||
|
int result_code; // Код результата обработки. [file:21]
|
||||||
|
char buffer[SHM_BUFFER_SIZE]; // Буфер строки. [file:21]
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name>\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *shm_name = argv[1];
|
||||||
|
const char *sem_client_name = argv[2];
|
||||||
|
const char *sem_server_name = argv[3];
|
||||||
|
|
||||||
|
// Открываем существующий shm. [file:21]
|
||||||
|
int shm_fd = shm_open(shm_name, O_RDWR, 0);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
shared_block_t *shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
close(shm_fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем семафоры. [file:21]
|
||||||
|
sem_t *sem_client = sem_open(sem_client_name, 0);
|
||||||
|
if (sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_server = sem_open(sem_server_name, 0);
|
||||||
|
if (sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем input.txt. [file:22]
|
||||||
|
FILE *fin = fopen("input.txt", "r");
|
||||||
|
if (!fin) {
|
||||||
|
perror("fopen(input.txt)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char input[SHM_BUFFER_SIZE];
|
||||||
|
|
||||||
|
while (fgets(input, sizeof(input), fin) != NULL) {
|
||||||
|
size_t len = strlen(input);
|
||||||
|
|
||||||
|
if (len > 0 && input[len - 1] == '\n') {
|
||||||
|
input[len - 1] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
|
||||||
|
strncpy(shm_ptr->buffer, input, SHM_BUFFER_SIZE - 1);
|
||||||
|
shm_ptr->buffer[SHM_BUFFER_SIZE - 1] = '\0';
|
||||||
|
|
||||||
|
shm_ptr->has_data = 1;
|
||||||
|
|
||||||
|
if (sem_post(sem_client) == -1) {
|
||||||
|
perror("sem_post(sem_client)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_wait(sem_server) == -1) {
|
||||||
|
perror("sem_wait(sem_server)");
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shm_ptr->result_code != 0) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Server reported error, result_code = %d\n",
|
||||||
|
shm_ptr->result_code);
|
||||||
|
fclose(fin);
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_close(sem_server);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("%s\n", shm_ptr->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fclose(fin) == EOF) {
|
||||||
|
perror("fclose(input.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_close(sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_close(sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
6
vlad/lab_6/input.txt
Normal file
6
vlad/lab_6/input.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
abacaba
|
||||||
|
xxxxxx
|
||||||
|
hello
|
||||||
|
aaaaa
|
||||||
|
1abc1d1e1
|
||||||
|
qwerty
|
||||||
210
vlad/lab_6/server.c
Normal file
210
vlad/lab_6/server.c
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
// server.c
|
||||||
|
// Сервер POSIX IPC: разделяемая память + именованные семафоры. [file:21]
|
||||||
|
// Задача: во всех парах одинаковых соседних символов второй символ заменить на пробел. [file:22]
|
||||||
|
|
||||||
|
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fprintf
|
||||||
|
#include <stdlib.h> // exit, EXIT_FAILURE, strtoul
|
||||||
|
#include <string.h> // memset, strncpy, strlen
|
||||||
|
#include <errno.h> // errno
|
||||||
|
#include <fcntl.h> // O_CREAT, O_EXCL, O_RDWR
|
||||||
|
#include <sys/mman.h> // shm_open, mmap, munmap
|
||||||
|
#include <sys/stat.h> // S_IRUSR, S_IWUSR
|
||||||
|
#include <semaphore.h> // sem_t, sem_open, sem_close, sem_unlink, sem_wait, sem_post
|
||||||
|
#include <unistd.h> // ftruncate, close
|
||||||
|
|
||||||
|
#define SHM_BUFFER_SIZE 1024 // Максимальный размер строки в shared memory. [file:21]
|
||||||
|
|
||||||
|
// Структура разделяемой памяти. [file:21]
|
||||||
|
typedef struct {
|
||||||
|
int has_data; // 1, если клиент записал строку. [file:21]
|
||||||
|
int result_code; // 0 - успех, -1 - ошибка. [file:21]
|
||||||
|
char buffer[SHM_BUFFER_SIZE]; // Буфер для строки. [file:21]
|
||||||
|
} shared_block_t;
|
||||||
|
|
||||||
|
// Обработка строки по новому заданию: [file:22]
|
||||||
|
// "Во всех парах одинаковых символов второй символ заменить на пробел".
|
||||||
|
static void process_line(char *s) {
|
||||||
|
if (!s) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (size_t i = 0; s[i] != '\0'; ++i) {
|
||||||
|
// Идём по всей строке. [file:22]
|
||||||
|
if (s[i] != '\0' && s[i + 1] != '\0' && s[i] == s[i + 1]) {
|
||||||
|
// Если два соседних символа равны, второй заменяем на пробел. [file:22]
|
||||||
|
s[i + 1] = ' ';
|
||||||
|
// Можно сдвинуться дальше, чтобы не склеивать новые пары искусственно. [file:22]
|
||||||
|
// Но по условию достаточно просто заменить второй символ.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// argv[1] - имя shm, argv[2] - имя sem_client, argv[3] - имя sem_server, argv[4] - итерации. [file:22]
|
||||||
|
if (argc < 4) {
|
||||||
|
fprintf(stderr,
|
||||||
|
"Usage: %s <shm_name> <sem_client_name> <sem_server_name> [iterations]\n",
|
||||||
|
argv[0]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *shm_name = argv[1];
|
||||||
|
const char *sem_client_name = argv[2];
|
||||||
|
const char *sem_server_name = argv[3];
|
||||||
|
|
||||||
|
int iterations = -1; // -1 = работать до сигнала/внешнего завершения. [file:22]
|
||||||
|
if (argc >= 5) {
|
||||||
|
char *endptr = NULL;
|
||||||
|
unsigned long tmp = strtoul(argv[4], &endptr, 10);
|
||||||
|
if (endptr == argv[4] || *endptr != '\0') {
|
||||||
|
fprintf(stderr, "Invalid iterations value: '%s'\n", argv[4]);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
iterations = (int) tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Простая зачистка возможных старых IPC-объектов. [file:21]
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
sem_unlink(sem_server_name);
|
||||||
|
|
||||||
|
// Создаём shared memory. [file:21]
|
||||||
|
int shm_fd = shm_open(shm_name,
|
||||||
|
O_CREAT | O_EXCL | O_RDWR,
|
||||||
|
S_IRUSR | S_IWUSR);
|
||||||
|
if (shm_fd == -1) {
|
||||||
|
perror("shm_open");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ftruncate(shm_fd, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("ftruncate");
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
shared_block_t *shm_ptr = mmap(NULL,
|
||||||
|
sizeof(shared_block_t),
|
||||||
|
PROT_READ | PROT_WRITE,
|
||||||
|
MAP_SHARED,
|
||||||
|
shm_fd,
|
||||||
|
0);
|
||||||
|
if (shm_ptr == MAP_FAILED) {
|
||||||
|
perror("mmap");
|
||||||
|
close(shm_fd);
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (close(shm_fd) == -1) {
|
||||||
|
perror("close");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Инициализация shared memory. [file:21]
|
||||||
|
shm_ptr->has_data = 0;
|
||||||
|
shm_ptr->result_code = 0;
|
||||||
|
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
|
||||||
|
|
||||||
|
// Создаём семафоры. [file:21]
|
||||||
|
sem_t *sem_client = sem_open(sem_client_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0);
|
||||||
|
if (sem_client == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_client)");
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
sem_t *sem_server = sem_open(sem_server_name,
|
||||||
|
O_CREAT | O_EXCL,
|
||||||
|
S_IRUSR | S_IWUSR,
|
||||||
|
0);
|
||||||
|
if (sem_server == SEM_FAILED) {
|
||||||
|
perror("sem_open(sem_server)");
|
||||||
|
sem_close(sem_client);
|
||||||
|
sem_unlink(sem_client_name);
|
||||||
|
munmap(shm_ptr, sizeof(shared_block_t));
|
||||||
|
shm_unlink(shm_name);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открываем файл вывода. [file:22]
|
||||||
|
FILE *fout = fopen("output.txt", "w");
|
||||||
|
if (!fout) {
|
||||||
|
perror("fopen(output.txt)");
|
||||||
|
// Продолжаем работать только через shared memory. [file:21]
|
||||||
|
}
|
||||||
|
|
||||||
|
int processed_count = 0; // Сколько строк обработано. [file:22]
|
||||||
|
|
||||||
|
while (iterations < 0 || processed_count < iterations) {
|
||||||
|
// Ждём строку от клиента. [file:21]
|
||||||
|
if (sem_wait(sem_client) == -1) {
|
||||||
|
perror("sem_wait(sem_client)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shm_ptr->has_data) {
|
||||||
|
fprintf(stderr, "Warning: sem_client posted, but has_data == 0\n");
|
||||||
|
shm_ptr->result_code = -1;
|
||||||
|
} else {
|
||||||
|
// Обрабатываем строку по новому заданию. [file:22]
|
||||||
|
process_line(shm_ptr->buffer);
|
||||||
|
|
||||||
|
shm_ptr->result_code = 0;
|
||||||
|
shm_ptr->has_data = 0;
|
||||||
|
processed_count++;
|
||||||
|
|
||||||
|
if (fout) {
|
||||||
|
fprintf(fout, "%s\n", shm_ptr->buffer);
|
||||||
|
fflush(fout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сообщаем клиенту, что результат готов. [file:21]
|
||||||
|
if (sem_post(sem_server) == -1) {
|
||||||
|
perror("sem_post(sem_server)");
|
||||||
|
processed_count = -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fout && fclose(fout) == EOF) {
|
||||||
|
perror("fclose(output.txt)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выводим число операций или -1. [file:22]
|
||||||
|
if (processed_count >= 0) {
|
||||||
|
printf("%d\n", processed_count);
|
||||||
|
} else {
|
||||||
|
printf("-1\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Очистка IPC-объектов. [file:21]
|
||||||
|
if (sem_close(sem_client) == -1) {
|
||||||
|
perror("sem_close(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_close(sem_server) == -1) {
|
||||||
|
perror("sem_close(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sem_unlink(sem_client_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_client)");
|
||||||
|
}
|
||||||
|
if (sem_unlink(sem_server_name) == -1) {
|
||||||
|
perror("sem_unlink(sem_server)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
|
||||||
|
perror("munmap");
|
||||||
|
}
|
||||||
|
if (shm_unlink(shm_name) == -1) {
|
||||||
|
perror("shm_unlink");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
42
vlad/lab_7/Makefile
Normal file
42
vlad/lab_7/Makefile
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
CC = gcc
|
||||||
|
CFLAGS = -Wall -Wextra -std=c11 -g -pthread
|
||||||
|
|
||||||
|
MAX_REPL ?= 100
|
||||||
|
INPUT1 ?= in1.txt
|
||||||
|
OUTPUT1 ?= out1.txt
|
||||||
|
INPUT2 ?= in2.txt
|
||||||
|
OUTPUT2 ?= out2.txt
|
||||||
|
|
||||||
|
all: threads_pairs
|
||||||
|
|
||||||
|
threads_pairs: main.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $<
|
||||||
|
|
||||||
|
test_all: threads_pairs
|
||||||
|
@echo "=== Тест с двумя файлами ==="
|
||||||
|
@printf "aabb\nzzzz\n" > $(INPUT1)
|
||||||
|
@printf "hello\nkkk\n" > $(INPUT2)
|
||||||
|
./threads_pairs $(MAX_REPL) $(INPUT1) $(OUTPUT1) $(INPUT2) $(OUTPUT2)
|
||||||
|
@echo "--- $(INPUT1) -> $(OUTPUT1) ---"
|
||||||
|
@cat $(INPUT1)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT1)
|
||||||
|
@echo
|
||||||
|
@echo "--- $(INPUT2) -> $(OUTPUT2) ---"
|
||||||
|
@cat $(INPUT2)
|
||||||
|
@echo "-----"
|
||||||
|
@cat $(OUTPUT2)
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@echo "Очистка..."
|
||||||
|
rm -f threads_pairs
|
||||||
|
rm -f in1.txt out1.txt in2.txt out2.txt
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " all - build threads_pairs"
|
||||||
|
@echo " test_all - run all tests"
|
||||||
|
@echo " clean - remove binaries and test files"
|
||||||
|
@echo " help - show this help"
|
||||||
|
|
||||||
|
.PHONY: all test_one test_two test_all clean help
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user