Compare commits
29 Commits
eea51b9f9c
...
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 |
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;
|
||||
}
|
||||
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
|
||||
129
mine/rgz/fifo_client.c
Normal file
129
mine/rgz/fifo_client.c
Normal file
@@ -0,0 +1,129 @@
|
||||
// fifo_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>
|
||||
|
||||
#define FIFO_REQUEST "/tmp/fifo_request"
|
||||
#define FIFO_RESPONSE "/tmp/fifo_response"
|
||||
#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;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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
|
||||
300
vlad/lab_7/main.c
Normal file
300
vlad/lab_7/main.c
Normal file
@@ -0,0 +1,300 @@
|
||||
// threads_pairs.c
|
||||
// Лабораторная №7: многопоточное программирование. [file:22]
|
||||
// Задача: во всех парах одинаковых соседних символов второй символ заменить на пробел. [file:22]
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
// Обработка файла по задаче: во всех парах одинаковых символов второй заменить на пробел. [file:22]
|
||||
static int process_file_pairs(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;
|
||||
|
||||
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];
|
||||
unsigned char outc = c;
|
||||
|
||||
if (total_replacements < cap &&
|
||||
i + 1 < n &&
|
||||
(unsigned char) rbuf[i] == (unsigned char) rbuf[i + 1]) {
|
||||
outc = c;
|
||||
if (total_replacements < cap) {
|
||||
outc = c; // первый из пары остаётся
|
||||
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;
|
||||
i++;
|
||||
unsigned char c2 = (unsigned char) rbuf[i];
|
||||
outc = c2;
|
||||
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;
|
||||
}
|
||||
|
||||
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_pairs(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;
|
||||
}
|
||||
}
|
||||
51
vlad/lab_8/Makefile
Normal file
51
vlad/lab_8/Makefile
Normal file
@@ -0,0 +1,51 @@
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -std=c11 -g
|
||||
|
||||
all: server_tcp_pairs client_tcp_pairs
|
||||
|
||||
server_tcp_pairs: server.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
client_tcp_pairs: client.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
test_server: server_tcp_pairs
|
||||
@echo "=== Запуск TCP-сервера (пары одинаковых символов) ==="
|
||||
@echo "Выходной файл: out.txt"
|
||||
./server_tcp_pairs 5000 out.txt
|
||||
|
||||
test_client: client_tcp_pairs
|
||||
@echo "=== Запуск TCP-клиента ==="
|
||||
@echo "Создаём input.txt"
|
||||
@printf "aabbccddeeff\nabba\nxxxxx\n" > input.txt
|
||||
./client_tcp_pairs 127.0.0.1 5000 input.txt
|
||||
|
||||
test_all: all
|
||||
@echo "=== Автотест TCP (пары одинаковых символов) ==="
|
||||
@printf "aabbccddeeff\nabba\nxxxxx\n" > input.txt
|
||||
./server_tcp_pairs 5000 out.txt & \
|
||||
SRV=$$!; \
|
||||
sleep 1; \
|
||||
./client_tcp_pairs 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_tcp_pairs client_tcp_pairs
|
||||
rm -f input.txt out.txt
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " all - build server_tcp_pairs and client_tcp_pairs"
|
||||
@echo " test_server - run server (port 5000, out.txt)"
|
||||
@echo " test_client - run client to send input.txt"
|
||||
@echo " test_all - end-to-end TCP test"
|
||||
@echo " clean - remove binaries and test files"
|
||||
@echo " help - show this help"
|
||||
|
||||
.PHONY: all test_server test_client test_all clean help
|
||||
|
||||
139
vlad/lab_8/client.c
Normal file
139
vlad/lab_8/client.c
Normal file
@@ -0,0 +1,139 @@
|
||||
// client_tcp_pairs.c
|
||||
// TCP-клиент для лабораторной №8, вариант "во всех парах одинаковых символов
|
||||
// второй символ заменить на пробел".
|
||||
// Клиент читает входной файл и передаёт его содержимое серверу по TCP.
|
||||
|
||||
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fread
|
||||
#include <stdlib.h> // exit, EXIT_FAILURE, strtol
|
||||
#include <string.h> // memset, strlen
|
||||
#include <errno.h> // errno
|
||||
#include <unistd.h> // close, write
|
||||
#include <arpa/inet.h> // sockaddr_in, inet_pton, htons
|
||||
#include <sys/socket.h> // socket, connect
|
||||
#include <sys/types.h> // типы сокетов
|
||||
#include <netinet/in.h> // sockaddr_in
|
||||
|
||||
#define BUF_SIZE 4096
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
// Ожидаемые аргументы:
|
||||
// argv[1] - IP-адрес сервера (например, 127.0.0.1).
|
||||
// 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 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;
|
||||
}
|
||||
|
||||
// Создаём TCP-сокет.
|
||||
int sockfd = socket(AF_INET, SOCK_STREAM, 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);
|
||||
|
||||
// Переводим строковый IP в бинарную форму.
|
||||
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;
|
||||
}
|
||||
|
||||
// Устанавливаем TCP-соединение.
|
||||
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("connect");
|
||||
close(sockfd);
|
||||
fclose(fin);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("Connected to %s:%d, sending file '%s'\n",
|
||||
server_ip, port, input_path);
|
||||
|
||||
char buf[BUF_SIZE];
|
||||
|
||||
for (;;) {
|
||||
// Читаем блок из файла.
|
||||
size_t n = fread(buf, 1, sizeof(buf), fin);
|
||||
if (n > 0) {
|
||||
// Отправляем блок по TCP.
|
||||
size_t sent_total = 0;
|
||||
while (sent_total < n) {
|
||||
ssize_t sent = write(sockfd,
|
||||
buf + sent_total,
|
||||
n - sent_total);
|
||||
if (sent < 0) {
|
||||
perror("write");
|
||||
close(sockfd);
|
||||
fclose(fin);
|
||||
return -1;
|
||||
}
|
||||
sent_total += (size_t)sent;
|
||||
}
|
||||
}
|
||||
|
||||
// Если прочитали меньше, чем BUF_SIZE, либо 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)");
|
||||
}
|
||||
|
||||
// Корректно закрываем соединение, чтобы сервер получил EOF.
|
||||
if (shutdown(sockfd, SHUT_WR) < 0) {
|
||||
perror("shutdown");
|
||||
}
|
||||
|
||||
close(sockfd);
|
||||
|
||||
printf("File '%s' sent to %s:%d, connection closed.\n",
|
||||
input_path, server_ip, port);
|
||||
|
||||
return 0;
|
||||
}
|
||||
189
vlad/lab_8/server.c
Normal file
189
vlad/lab_8/server.c
Normal file
@@ -0,0 +1,189 @@
|
||||
// server_tcp_pairs.c
|
||||
// Лабораторная №8, протокол TCP (нечётные варианты, но здесь по заданию TCP).
|
||||
// Задача: во всех парах одинаковых символов второй символ заменить на пробел,
|
||||
// считать количество замен и сохранить обработанный текст в выходной файл.
|
||||
|
||||
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fwrite
|
||||
#include <stdlib.h> // exit, EXIT_FAILURE, strtol
|
||||
#include <string.h> // memset, strlen
|
||||
#include <errno.h> // errno
|
||||
#include <unistd.h> // close, read, write
|
||||
#include <arpa/inet.h> // sockaddr_in, inet_ntoa, htons, htonl, ntohs, ntohl
|
||||
#include <sys/socket.h> // socket, bind, listen, accept
|
||||
#include <sys/types.h> // типы сокетов
|
||||
#include <netinet/in.h> // структура sockaddr_in
|
||||
|
||||
#define BUF_SIZE 4096 // Размер буфера приёма из TCP-сокета.
|
||||
|
||||
// Функция обрабатывает блок данных, заменяя во всех парах одинаковых подряд
|
||||
// идущих символов второй символ пары на пробел. Пары могут пересекать границу
|
||||
// буферов, поэтому учитывается последний символ предыдущего блока.
|
||||
static void process_block_pairs(char *buf,
|
||||
ssize_t len,
|
||||
int *has_prev,
|
||||
unsigned char *prev_char,
|
||||
long long *repl_counter) {
|
||||
if (!buf || !has_prev || !prev_char || !repl_counter) {
|
||||
return; // Проверка входных указателей.
|
||||
}
|
||||
|
||||
for (ssize_t i = 0; i < len; i++) {
|
||||
unsigned char c = (unsigned char) buf[i];
|
||||
|
||||
if (*has_prev) {
|
||||
// Есть предыдущий символ из этого же потока.
|
||||
if (c == *prev_char) {
|
||||
// Найдена пара одинаковых подряд символов.
|
||||
buf[i] = ' '; // Заменяем второй символ пары на пробел.
|
||||
(*repl_counter)++; // Увеличиваем счётчик замен.
|
||||
}
|
||||
*has_prev = 0; // Сбрасываем флаг: пара уже обработана.
|
||||
} else {
|
||||
// Текущий символ станет предыдущим для возможной пары в следующем байте.
|
||||
*prev_char = c;
|
||||
*has_prev = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// Ожидаемые аргументы:
|
||||
// argv[1] - порт TCP сервера (например, 5000).
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Создаём TCP-сокет.
|
||||
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (listen_fd < 0) {
|
||||
perror("socket");
|
||||
fclose(fout);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Включаем SO_REUSEADDR, чтобы можно было быстро перезапускать сервер.
|
||||
int optval = 1;
|
||||
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
|
||||
&optval, sizeof(optval)) < 0) {
|
||||
perror("setsockopt(SO_REUSEADDR)");
|
||||
close(listen_fd);
|
||||
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(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
|
||||
perror("bind");
|
||||
close(listen_fd);
|
||||
fclose(fout);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Переводим сокет в режим прослушивания.
|
||||
if (listen(listen_fd, 1) < 0) {
|
||||
perror("listen");
|
||||
close(listen_fd);
|
||||
fclose(fout);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("TCP server (pairs) listening on port %d, output file: %s\n",
|
||||
port, out_path);
|
||||
|
||||
// Принимаем одно соединение от клиента.
|
||||
struct sockaddr_in cliaddr;
|
||||
socklen_t cli_len = sizeof(cliaddr);
|
||||
int conn_fd = accept(listen_fd, (struct sockaddr *) &cliaddr, &cli_len);
|
||||
if (conn_fd < 0) {
|
||||
perror("accept");
|
||||
close(listen_fd);
|
||||
fclose(fout);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("Client connected from %s:%d\n",
|
||||
inet_ntoa(cliaddr.sin_addr),
|
||||
ntohs(cliaddr.sin_port));
|
||||
|
||||
close(listen_fd); // Больше новых клиентов не принимаем.
|
||||
|
||||
char buf[BUF_SIZE];
|
||||
long long repl_counter = 0; // Общее количество замен.
|
||||
int has_prev = 0; // Был ли предыдущий символ для пары.
|
||||
unsigned char prev_char = 0; // Предыдущий символ, если has_prev == 1.
|
||||
|
||||
for (;;) {
|
||||
// Считываем данные из TCP-сокета.
|
||||
ssize_t n = read(conn_fd, buf, sizeof(buf));
|
||||
if (n > 0) {
|
||||
// Обрабатываем блок на предмет пар одинаковых символов.
|
||||
process_block_pairs(buf, n, &has_prev, &prev_char, &repl_counter);
|
||||
|
||||
// Пишем обработанный блок в выходной файл.
|
||||
if (fwrite(buf, 1, (size_t) n, fout) != (size_t) n) {
|
||||
perror("fwrite");
|
||||
repl_counter = -1;
|
||||
break;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
// Клиент корректно закрыл соединение.
|
||||
printf("Client disconnected.\n");
|
||||
break;
|
||||
} else {
|
||||
// Ошибка при чтении.
|
||||
perror("read");
|
||||
repl_counter = -1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Закрываем соединение.
|
||||
close(conn_fd);
|
||||
|
||||
// Закрываем файл.
|
||||
if (fclose(fout) == EOF) {
|
||||
perror("fclose(output_file)");
|
||||
repl_counter = -1;
|
||||
}
|
||||
|
||||
printf("Total replacements (pairs): %lld\n", repl_counter);
|
||||
if (repl_counter < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
19
vlad/rgz/Makefile
Normal file
19
vlad/rgz/Makefile
Normal file
@@ -0,0 +1,19 @@
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -O2
|
||||
LDFLAGS =
|
||||
|
||||
SERVER = daemon
|
||||
CLIENT = client
|
||||
|
||||
.PHONY: all clean
|
||||
|
||||
all: daemon client
|
||||
|
||||
daemon: daemon.c
|
||||
$(CC) $(CFLAGS) -o $(SERVER) daemon.c $(LDFLAGS)
|
||||
|
||||
client: client.c
|
||||
$(CC) $(CFLAGS) -o $(CLIENT) client.c $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f daemon client
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user