Compare commits
6 Commits
c0b7b1b869
...
baa8b5be9b
| Author | SHA1 | Date | |
|---|---|---|---|
| baa8b5be9b | |||
| 47812b3900 | |||
| 69a2b7087c | |||
| afa6d4a7c2 | |||
| 1b46875e81 | |||
| 96015acb09 |
61
lab_7/Makefile
Normal file
61
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
|
||||
43
lab_7/kirill/Makefile
Normal file
43
lab_7/kirill/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
lab_7/kirill/main.c
Normal file
276
lab_7/kirill/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;
|
||||
}
|
||||
}
|
||||
301
lab_7/threads_var12.c
Normal file
301
lab_7/threads_var12.c
Normal file
@@ -0,0 +1,301 @@
|
||||
// threads_var12.c
|
||||
// Лабораторная №7: многопоточное программирование. [file:22]
|
||||
// Вариант 12: "Заменить на пробелы все символы, совпадающие с первым символом в строке, кроме первого". [file:22]
|
||||
// Для каждого входного файла создаётся отдельный поток, который выполняет обработку. [file:22]
|
||||
|
||||
#include <stdio.h> // printf, fprintf, perror
|
||||
#include <stdlib.h> // exit, EXIT_FAILURE, strtol
|
||||
#include <string.h> // strlen, strerror, memset
|
||||
#include <errno.h> // errno
|
||||
#include <unistd.h> // read, write, close
|
||||
#include <fcntl.h> // open, O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC
|
||||
#include <sys/stat.h> // режимы доступа к файлам
|
||||
#include <pthread.h> // pthread_t, pthread_create, pthread_join, pthread_mutex_t [file:21]
|
||||
|
||||
#define RBUFSZ 4096 // Размер буфера чтения. [file:73]
|
||||
#define WBUFSZ 4096 // Размер буфера записи. [file:73]
|
||||
#define MAX_THREADS 100 // Ограничение на количество потоков. [file:22]
|
||||
|
||||
// Структура для параметров потока: имена файлов и лимит замен. [file:22]
|
||||
typedef struct {
|
||||
const char *input_path; // Имя входного файла. [file:72]
|
||||
const char *output_path; // Имя выходного файла. [file:72]
|
||||
long long max_repl; // Максимальное количество замен для данного файла. [file:73]
|
||||
int thread_index; // Индекс потока для логирования. [file:22]
|
||||
int result; // Код завершения потока (0 или -1). [file:22]
|
||||
} ThreadTask;
|
||||
|
||||
// Глобальный мьютекс для синхронизации вывода в терминал. [file:22]
|
||||
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
// Потокобезопасная функция вывода сообщений об ошибках. [file:73]
|
||||
static void die_perror_thread(const char *what,
|
||||
const char *path,
|
||||
int exit_code) {
|
||||
int saved = errno; // Сохраняем errno, чтобы не потерять код ошибки. [file:73]
|
||||
char msg[512]; // Локальный буфер для сообщения. [file:73]
|
||||
|
||||
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); // Захватываем мьютекс для безопасного вывода. [file:22]
|
||||
write(STDERR_FILENO, msg, strlen(msg)); // Пишем сообщение в stderr. [file:73]
|
||||
pthread_mutex_unlock(&log_mutex); // Освобождаем мьютекс. [file:22]
|
||||
|
||||
(void) exit_code; // В потоке не выходим из процесса, код возврата ставится в структуре. [file:22]
|
||||
}
|
||||
|
||||
// Разбор положительного long long из строки. [file:73]
|
||||
static long long parse_ll(const char *s) {
|
||||
char *end = NULL;
|
||||
errno = 0;
|
||||
long long v = strtoll(s, &end, 10); // Преобразование строки в 64-битное целое. [file:73]
|
||||
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// Функция, реализующая функциональность ЛР2 для одного файла. [file:73]
|
||||
static int process_file_variant12(const char *in_path,
|
||||
const char *out_path,
|
||||
long long cap) {
|
||||
int in_fd = open(in_path, O_RDONLY); // Открываем входной файл для чтения. [file:73]
|
||||
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; // rw-rw-rw-. [file:73]
|
||||
|
||||
int out_fd = open(out_path,
|
||||
O_CREAT | O_WRONLY | O_TRUNC,
|
||||
perms); // Создаём/очищаем выходной файл. [file:73]
|
||||
if (out_fd < 0) {
|
||||
die_perror_thread("open output failed", out_path, -1);
|
||||
close(in_fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
char rbuf[RBUFSZ]; // Буфер для чтения. [file:73]
|
||||
char wbuf[WBUFSZ]; // Буфер для записи. [file:73]
|
||||
size_t wlen = 0; // Текущая длина буфера записи. [file:73]
|
||||
|
||||
long long total_replacements = 0; // Общее число замен по всему файлу. [file:73]
|
||||
|
||||
int at_line_start = 1; // Флаг: в начале строки. [file:73]
|
||||
unsigned char line_key = 0; // Первый символ текущей строки. [file:73]
|
||||
|
||||
for (;;) {
|
||||
ssize_t n = read(in_fd, rbuf, sizeof(rbuf)); // Читаем блок из файла. [file:73]
|
||||
if (n > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char) rbuf[i]; // Текущий символ. [file:73]
|
||||
|
||||
if (at_line_start) {
|
||||
// Если это первый символ в строке. [file:73]
|
||||
line_key = c; // Запоминаем его как ключ. [file:73]
|
||||
at_line_start = 0; // Больше не начало строки. [file:73]
|
||||
}
|
||||
|
||||
unsigned char outc = c; // По умолчанию символ не меняется. [file:73]
|
||||
|
||||
if (c == '\n') {
|
||||
// Конец строки. [file:73]
|
||||
at_line_start = 1; // Следующий символ будет началом новой строки. [file:73]
|
||||
} else if (c == line_key) {
|
||||
if (total_replacements < cap) {
|
||||
outc = ' '; // Заменяем на пробел. [file:22]
|
||||
total_replacements++;
|
||||
}
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
ssize_t wrote = write(out_fd, wbuf, wlen); // Сбрасываем буфер в файл. [file:73]
|
||||
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; // Добавляем символ в буфер записи. [file:73]
|
||||
}
|
||||
} else if (n == 0) {
|
||||
if (wlen > 0) {
|
||||
// Если остались несброшенные данные. [file:73]
|
||||
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; // Достигнут конец файла. [file:73]
|
||||
} 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); // Печать числа замен в stdout под мьютексом. [file:22]
|
||||
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;
|
||||
}
|
||||
|
||||
// Функция потока: обёртка над process_file_variant12. [file:22]
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// Головной поток: создаёт потоки, ждёт их завершения и выводит статистику. [file:22]
|
||||
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];
|
||||
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;
|
||||
}
|
||||
}
|
||||
42
lab_7/vlad/Makefile
Normal file
42
lab_7/vlad/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
lab_7/vlad/main.c
Normal file
300
lab_7/vlad/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;
|
||||
}
|
||||
}
|
||||
50
lab_8/Makefile
Normal file
50
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
|
||||
117
lab_8/client.c
Normal file
117
lab_8/client.c
Normal file
@@ -0,0 +1,117 @@
|
||||
// client_udp.c
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <arpa/inet.h> // inet_pton, sockaddr_in [web:74]
|
||||
#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 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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
50
lab_8/kirill/Makefile
Normal file
50
lab_8/kirill/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
lab_8/kirill/client.c
Normal file
117
lab_8/kirill/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
lab_8/kirill/server.c
Normal file
142
lab_8/kirill/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;
|
||||
}
|
||||
176
lab_8/server.c
Normal file
176
lab_8/server.c
Normal file
@@ -0,0 +1,176 @@
|
||||
// server_udp.c
|
||||
// Лабораторная №8, вариант (UDP, чётный номер):
|
||||
// "Заменить на пробелы все символы, совпадающие с первым символом в строке, кроме первого". [file:22]
|
||||
// Сервер UDP: принимает текстовые блоки от клиента, построчно обрабатывает и пишет в файл. [web:78]
|
||||
|
||||
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fgets
|
||||
#include <stdlib.h> // exit, EXIT_FAILURE, strtoul
|
||||
#include <string.h> // memset, strlen, strchr, strcpy, strncpy
|
||||
#include <errno.h> // errno
|
||||
#include <unistd.h> // close
|
||||
#include <arpa/inet.h> // sockaddr_in, inet_ntoa, htons, htonl, ntohs, ntohl
|
||||
#include <sys/socket.h> // socket, bind, recvfrom, sendto
|
||||
#include <sys/types.h> // типы сокетов
|
||||
|
||||
#define BUF_SIZE 4096 // Размер сетевого буфера. [web:78]
|
||||
|
||||
// Специальная строка для обозначения конца передачи. [web:81]
|
||||
#define END_MARKER "END_OF_TRANSMISSION"
|
||||
|
||||
// Функция обработки одной строки по условию варианта. [file:22]
|
||||
static void process_line(char *line,
|
||||
long long *repl_counter) {
|
||||
if (!line || !repl_counter) {
|
||||
return; // Защита от некорректных указателей. [file:22]
|
||||
}
|
||||
|
||||
size_t len = strlen(line); // Получаем длину строки. [file:73]
|
||||
if (len == 0) {
|
||||
return; // Пустая строка не обрабатывается. [file:22]
|
||||
}
|
||||
|
||||
char first = line[0]; // Первый символ строки – ключ для замен. [file:22]
|
||||
|
||||
// Проходим по строке начиная со второго символа. [file:22]
|
||||
for (size_t i = 1; i < len; ++i) {
|
||||
if (line[i] == first && line[i] != '\n') {
|
||||
// Заменяем совпадающий символ пробелом и увеличиваем счётчик. [file:22]
|
||||
line[i] = ' ';
|
||||
(*repl_counter)++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// Ожидаемые аргументы:
|
||||
// argv[1] - порт UDP сервера (например, 5000). [web:78]
|
||||
// argv[2] - имя выходного файла. [file:22]
|
||||
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;
|
||||
}
|
||||
|
||||
// Разбираем номер порта. [web:78]
|
||||
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:22]
|
||||
|
||||
FILE *fout = fopen(out_path, "w");
|
||||
if (!fout) {
|
||||
perror("fopen(output_file)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // Создаём UDP-сокет. [web:74]
|
||||
if (sockfd < 0) {
|
||||
perror("socket");
|
||||
fclose(fout);
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr)); // Обнуляем структуру адреса. [web:74]
|
||||
servaddr.sin_family = AF_INET; // IPv4. [web:74]
|
||||
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // Принимать на всех интерфейсах. [web:74]
|
||||
servaddr.sin_port = htons(port); // Порт сервера в сетевом порядке байт. [web:74]
|
||||
|
||||
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-пакетов. [web:78]
|
||||
char line_buf[BUF_SIZE]; // Буфер для накопления текущей строки. [file:22]
|
||||
size_t line_len = 0; // Текущая длина строки в line_buf. [file:22]
|
||||
long long total_replacements = 0; // Общее количество замен. [file:22]
|
||||
|
||||
int done = 0; // Флаг завершения при получении END_MARKER. [web:81]
|
||||
|
||||
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); // Принимаем UDP-дейтаграмму. [web:74]
|
||||
if (n < 0) {
|
||||
perror("recvfrom");
|
||||
total_replacements = -1;
|
||||
break;
|
||||
}
|
||||
|
||||
buf[n] = '\0'; // Делаем строку ASCIIZ для удобства. [web:78]
|
||||
|
||||
if (strcmp(buf, END_MARKER) == 0) {
|
||||
printf("Received END marker, finishing.\n");
|
||||
done = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
size_t pos = 0;
|
||||
while (pos < (size_t) n) {
|
||||
char c = buf[pos++];
|
||||
if (c == '\n') {
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
51
lab_8/vlad/Makefile
Normal file
51
lab_8/vlad/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
lab_8/vlad/client.c
Normal file
139
lab_8/vlad/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
lab_8/vlad/server.c
Normal file
189
lab_8/vlad/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;
|
||||
}
|
||||
Reference in New Issue
Block a user