kirill-refactor
This commit is contained in:
4
mine/lab_1/kirill`s/in.txt
Normal file
4
mine/lab_1/kirill`s/in.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
123456123456123456123456123456123456123456123456
|
||||
123456123456
|
||||
123456123456
|
||||
123456123456
|
||||
129
mine/lab_1/kirill`s/task18.c
Normal file
129
mine/lab_1/kirill`s/task18.c
Normal file
@@ -0,0 +1,129 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.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];
|
||||
int n;
|
||||
if (path) {
|
||||
n = snprintf(msg, sizeof(msg), "%s: %s: %s\n", what, path, strerror(saved));
|
||||
} else {
|
||||
n = snprintf(msg, sizeof(msg), "%s: %s\n", what, strerror(saved));
|
||||
}
|
||||
if (n > 0) (void) write(STDERR_FILENO, msg, (size_t) n);
|
||||
_exit(exit_code);
|
||||
}
|
||||
|
||||
static void xwrite_all(int fd, const char *buf, size_t len, const char *path) {
|
||||
size_t off = 0;
|
||||
while (off < len) {
|
||||
ssize_t n = write(fd, buf + off, len - off);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
die_perror("write failed", path, -1);
|
||||
}
|
||||
off += (size_t) n;
|
||||
}
|
||||
}
|
||||
|
||||
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 != 4) {
|
||||
const char *usage =
|
||||
"Usage: lab1_var_thirds_line <input.txt> <output.txt> <max_replacements>\n"
|
||||
"Replace every third non-newline byte in each line with a space; counter resets after LF.\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]);
|
||||
if (cap < 0) die_perror("invalid max_replacements", argv[3], -1);
|
||||
|
||||
int in_fd = open(in_path, O_RDONLY);
|
||||
if (in_fd < 0) die_perror("open input failed", in_path, -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("open output failed", out_path, -1);
|
||||
|
||||
char rbuf[RBUFSZ];
|
||||
char wbuf[WBUFSZ];
|
||||
size_t wlen = 0;
|
||||
|
||||
long long total = 0;
|
||||
long long col = 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 (c == '\n') {
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = '\n';
|
||||
col = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char outc = c;
|
||||
|
||||
col++;
|
||||
|
||||
if (replacing_enabled && (col % 3 == 0) && total < cap) {
|
||||
outc = ' ';
|
||||
total++;
|
||||
if (total == cap) replacing_enabled = 0;
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) outc;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
if (wlen > 0) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
if (errno == EINTR) continue;
|
||||
die_perror("read failed", in_path, -1);
|
||||
}
|
||||
}
|
||||
|
||||
if (close(in_fd) < 0) die_perror("close input failed", in_path, -1);
|
||||
if (close(out_fd) < 0) die_perror("close output failed", out_path, -1);
|
||||
|
||||
char res[64];
|
||||
int m = snprintf(res, sizeof(res), "%lld\n", total);
|
||||
if (m > 0) (void) write(STDOUT_FILENO, res, (size_t) m);
|
||||
|
||||
return 0;
|
||||
}
|
||||
52
mine/lab_2/kirill/Makefile
Normal file
52
mine/lab_2/kirill/Makefile
Normal file
@@ -0,0 +1,52 @@
|
||||
# Makefile
|
||||
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -O2
|
||||
PICFLAGS = -fPIC
|
||||
|
||||
.PHONY: all dynamic static test-dynamic test-static clean
|
||||
|
||||
all: dynamic static
|
||||
|
||||
# --- Dynamic (shared) build ---
|
||||
dynamic: libtext.so main_d
|
||||
|
||||
libtext.so: lib_d.o
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
main_d: main_d.o
|
||||
$(CC) -o $@ $^ -ldl
|
||||
|
||||
lib_d.o: lib_d.c
|
||||
$(CC) $(CFLAGS) $(PICFLAGS) -c $< -o $@
|
||||
|
||||
# --- Static build ---
|
||||
static: libtext.a main_s
|
||||
|
||||
libtext.a: lib_s.o
|
||||
ar rcs $@ $^
|
||||
|
||||
main_s: main_s.o libtext.a
|
||||
$(CC) -o $@ main_s.o libtext.a
|
||||
|
||||
# Generic rule for other .o files
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
|
||||
# --- Test targets ---
|
||||
# Creates a small `test_input.txt`, runs the program, and shows `out.txt`
|
||||
test-dynamic: dynamic
|
||||
printf "Hello123456789\nLine2abc\n" > test_input.txt
|
||||
./main_d test_input.txt out.txt 100 ./libtext.so
|
||||
@echo "---- out.txt ----"
|
||||
cat out.txt
|
||||
|
||||
test-static: static
|
||||
printf "Hello123456789\nLine2abc\n" > test_input.txt
|
||||
./main_s test_input.txt out.txt 100
|
||||
@echo "---- out.txt ----"
|
||||
cat out.txt
|
||||
|
||||
# --- Cleanup ---
|
||||
clean:
|
||||
rm -f *.o *.so *.a main_d main_s test_input.txt out.txt
|
||||
18
mine/lab_2/kirill/lib_d.c
Normal file
18
mine/lab_2/kirill/lib_d.c
Normal file
@@ -0,0 +1,18 @@
|
||||
#include <string.h>
|
||||
|
||||
int replace_char_line(char *buf, int key, int *replacements_left) {
|
||||
(void)key;
|
||||
int replaced = 0;
|
||||
int count = 0;
|
||||
|
||||
for (size_t i = 0; buf[i] != '\0'; i++) {
|
||||
if (buf[i] == '\n') continue;
|
||||
count++;
|
||||
if (count % 3 == 0 && *replacements_left > 0) {
|
||||
buf[i] = ' ';
|
||||
replaced++;
|
||||
(*replacements_left)--;
|
||||
}
|
||||
}
|
||||
return replaced;
|
||||
}
|
||||
19
mine/lab_2/kirill/lib_s.c
Normal file
19
mine/lab_2/kirill/lib_s.c
Normal file
@@ -0,0 +1,19 @@
|
||||
#include <stddef.h>
|
||||
|
||||
int replace_char_line(char *buf, int key, int *replacements_left) {
|
||||
(void)key;
|
||||
int replaced = 0;
|
||||
int count = 0;
|
||||
|
||||
for (size_t i = 0; buf[i] != '\0'; i++) {
|
||||
if (buf[i] == '\n') continue;
|
||||
count++;
|
||||
if (count % 3 == 0 && *replacements_left > 0) {
|
||||
buf[i] = ' ';
|
||||
replaced++;
|
||||
(*replacements_left)--;
|
||||
if (*replacements_left == 0) break;
|
||||
}
|
||||
}
|
||||
return replaced;
|
||||
}
|
||||
62
mine/lab_2/kirill/main_d.c
Normal file
62
mine/lab_2/kirill/main_d.c
Normal file
@@ -0,0 +1,62 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#define MAX_LINE 4096
|
||||
|
||||
typedef int (*replace_func_t)(char*, int, int*);
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 5) {
|
||||
fprintf(stderr, "Usage: %s <in> <out> <cap> <path_to_so>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
FILE *fin = fopen(argv[1], "r");
|
||||
if (!fin) { perror("fopen input"); return 1; }
|
||||
FILE *fout = fopen(argv[2], "w");
|
||||
if (!fout) { perror("fopen output"); fclose(fin); return 1; }
|
||||
|
||||
int cap = atoi(argv[3]);
|
||||
if (cap < 0) {
|
||||
fprintf(stderr, "invalid cap\n");
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void *lib = dlopen(argv[4], RTLD_LAZY);
|
||||
if (!lib) {
|
||||
fprintf(stderr, "dlopen error: %s\n", dlerror());
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
return 1;
|
||||
}
|
||||
|
||||
replace_func_t replace = (replace_func_t)dlsym(lib, "replace_char_line");
|
||||
if (!replace) {
|
||||
fprintf(stderr, "dlsym error: %s\n", dlerror());
|
||||
dlclose(lib);
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int total = 0;
|
||||
char line[MAX_LINE];
|
||||
|
||||
while (fgets(line, sizeof(line), fin)) {
|
||||
if (cap > 0) {
|
||||
int key = (unsigned char)line[0];
|
||||
int repl_line = replace(line, key, &cap);
|
||||
total += repl_line;
|
||||
}
|
||||
fputs(line, fout);
|
||||
}
|
||||
|
||||
dlclose(lib);
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
printf("total_replacements: %d\n", total);
|
||||
return 0;
|
||||
}
|
||||
44
mine/lab_2/kirill/main_s.c
Normal file
44
mine/lab_2/kirill/main_s.c
Normal file
@@ -0,0 +1,44 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define MAX_LINE 4096
|
||||
|
||||
int replace_char_line(char *buf, int key, int *replacements_left);
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 4) {
|
||||
fprintf(stderr, "Usage: %s <in> <out> <cap>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
FILE *fin = fopen(argv[1], "r");
|
||||
if (!fin) { perror("fopen input"); return 1; }
|
||||
FILE *fout = fopen(argv[2], "w");
|
||||
if (!fout) { perror("fopen output"); fclose(fin); return 1; }
|
||||
|
||||
int cap = atoi(argv[3]);
|
||||
if (cap < 0) {
|
||||
fprintf(stderr, "invalid cap\n");
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int total = 0;
|
||||
char line[MAX_LINE];
|
||||
|
||||
while (fgets(line, sizeof(line), fin)) {
|
||||
if (cap > 0) {
|
||||
// key is unused, but pass the first byte for symmetry
|
||||
int key = (unsigned char)line[0];
|
||||
int repl_line = replace_char_line(line, key, &cap);
|
||||
total += repl_line;
|
||||
}
|
||||
fputs(line, fout);
|
||||
}
|
||||
|
||||
fclose(fin);
|
||||
fclose(fout);
|
||||
printf("total_replacements: %d\n", total);
|
||||
return 0;
|
||||
}
|
||||
55
mine/lab_3/kirill/Makefile
Normal file
55
mine/lab_3/kirill/Makefile
Normal file
@@ -0,0 +1,55 @@
|
||||
# Компилятор и флаги
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -std=c99 -pedantic
|
||||
|
||||
# Целевые файлы
|
||||
TARGET_PARENT = parent
|
||||
TARGET_LAB1 = task18
|
||||
|
||||
# Исходные файлы
|
||||
SRC_PARENT = parent.c
|
||||
SRC_LAB1 = task18.c
|
||||
|
||||
# Объектные файлы
|
||||
OBJ_PARENT = $(SRC_PARENT:.c=.o)
|
||||
OBJ_LAB1 = $(SRC_LAB1:.c=.o)
|
||||
|
||||
.PHONY: all clean help test
|
||||
|
||||
all: $(TARGET_PARENT) $(TARGET_LAB1)
|
||||
|
||||
$(TARGET_PARENT): $(OBJ_PARENT)
|
||||
$(CC) $(CFLAGS) -o $@ $^
|
||||
@echo "Родительская программа собрана: $@"
|
||||
|
||||
$(TARGET_LAB1): $(OBJ_LAB1)
|
||||
$(CC) $(CFLAGS) -o $@ $^
|
||||
@echo "Программа лаб. работы №1 собрана: $@"
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET_PARENT) $(TARGET_LAB1) $(OBJ_PARENT) $(OBJ_LAB1) *.txt
|
||||
@echo "Очистка завершена"
|
||||
|
||||
help:
|
||||
@echo "Доступные цели:"
|
||||
@echo " all - собрать все"
|
||||
@echo " clean - удалить все скомпилированные файлы"
|
||||
@echo " test - запустить тестирование программы"
|
||||
|
||||
test: all
|
||||
@echo "Создаем тестовые файлы..."
|
||||
@echo "22222222222222222222" > input1.txt
|
||||
@echo "2222222222222222222" >> input1.txt
|
||||
@echo "22222222222222222222" >> input1.txt
|
||||
@echo "Test line one in second file" > input2.txt
|
||||
@echo "Second line in second file" >> input2.txt
|
||||
@echo "Third line in second file" >> input2.txt
|
||||
@echo "Запуск parent..."
|
||||
@./$(TARGET_PARENT) 5 input1.txt output1.txt input2.txt output2.txt
|
||||
@echo "Содержимое output1.txt:"
|
||||
@cat output1.txt || echo "Файл output1.txt не найден"
|
||||
@echo "Содержимое output2.txt:"
|
||||
@cat output2.txt || echo "Файл output2.txt не найден"
|
||||
117
mine/lab_3/kirill/parent.c
Normal file
117
mine/lab_3/kirill/parent.c
Normal file
@@ -0,0 +1,117 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// Проверка аргументов командной строки
|
||||
if (argc < 4) {
|
||||
const char *usage =
|
||||
"Usage: parent <max_replacements> <input1.txt> <output1.txt> "
|
||||
"[<input2.txt> <output2.txt> ...]\n"
|
||||
" max_replacements: максимальное количество замен\n"
|
||||
" input/output: пары входных и выходных файлов\n";
|
||||
fprintf(stderr, "%s", usage);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Проверка четности количества файлов (пары input/output)
|
||||
if ((argc - 2) % 2 != 0) {
|
||||
fprintf(stderr, "Error: количество файлов должно быть четным (пары input/output)\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *max_replacements_arg = argv[1];
|
||||
int num_files = (argc - 2) / 2; // количество пар файлов
|
||||
|
||||
printf("Родительский процесс: PID=%d\n", getpid());
|
||||
printf("Будет запущено %d дочерних процессов\n", num_files);
|
||||
printf("Максимальное количество замен: %s\n\n", max_replacements_arg);
|
||||
|
||||
// Массив для хранения PID дочерних процессов
|
||||
pid_t *child_pids = malloc(num_files * sizeof(pid_t));
|
||||
if (child_pids == NULL) {
|
||||
perror("malloc failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Запуск дочерних процессов
|
||||
for (int i = 0; i < num_files; i++) {
|
||||
const char *input_file = argv[2 + i * 2];
|
||||
const char *output_file = argv[2 + i * 2 + 1];
|
||||
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid < 0) {
|
||||
// Ошибка при создании процесса
|
||||
perror("fork failed");
|
||||
|
||||
// Ждем завершения уже запущенных процессов
|
||||
for (int j = 0; j < i; j++) {
|
||||
int status;
|
||||
waitpid(child_pids[j], &status, 0);
|
||||
}
|
||||
|
||||
free(child_pids);
|
||||
return -1;
|
||||
|
||||
} else if (pid == 0) {
|
||||
// Код дочернего процесса
|
||||
printf("Дочерний процесс %d: PID=%d, обработка %s -> %s\n",
|
||||
i + 1, getpid(), input_file, output_file);
|
||||
|
||||
// Запуск программы из лабораторной работы №1
|
||||
execl("./task18", "task18", input_file, output_file, max_replacements_arg, (char *)NULL);
|
||||
|
||||
// Если execl вернул управление, произошла ошибка
|
||||
fprintf(stderr, "Дочерний процесс %d: execl failed для %s: %s\n",
|
||||
i + 1, input_file, strerror(errno));
|
||||
_exit(-1);
|
||||
|
||||
} else {
|
||||
// Код родительского процесса
|
||||
child_pids[i] = pid;
|
||||
}
|
||||
}
|
||||
|
||||
// Ожидание завершения всех дочерних процессов
|
||||
printf("\nРодительский процесс ожидает завершения дочерних процессов...\n\n");
|
||||
|
||||
for (int i = 0; i < num_files; i++) {
|
||||
int status;
|
||||
pid_t terminated_pid = waitpid(child_pids[i], &status, 0);
|
||||
|
||||
if (terminated_pid < 0) {
|
||||
perror("waitpid failed");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Проверка статуса завершения
|
||||
if (WIFEXITED(status)) {
|
||||
int exit_code = WEXITSTATUS(status);
|
||||
printf("Процесс %d (PID=%d) завершился нормально\n",
|
||||
i + 1, terminated_pid);
|
||||
|
||||
if (exit_code == 0) {
|
||||
printf(" Код завершения: %d (успех)\n", exit_code);
|
||||
} else {
|
||||
printf(" Код завершения: %d (ошибка)\n", exit_code);
|
||||
}
|
||||
} else if (WIFSIGNALED(status)) {
|
||||
int signal = WTERMSIG(status);
|
||||
printf("Процесс %d (PID=%d) был прерван сигналом %d\n",
|
||||
i + 1, terminated_pid, signal);
|
||||
} else {
|
||||
printf("Процесс %d (PID=%d) завершился с неизвестным статусом\n",
|
||||
i + 1, terminated_pid);
|
||||
}
|
||||
}
|
||||
|
||||
printf("\nВсе дочерние процессы завершены\n");
|
||||
|
||||
free(child_pids);
|
||||
return 0;
|
||||
}
|
||||
129
mine/lab_3/kirill/task18.c
Normal file
129
mine/lab_3/kirill/task18.c
Normal file
@@ -0,0 +1,129 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.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];
|
||||
int n;
|
||||
if (path) {
|
||||
n = snprintf(msg, sizeof(msg), "%s: %s: %s\n", what, path, strerror(saved));
|
||||
} else {
|
||||
n = snprintf(msg, sizeof(msg), "%s: %s\n", what, strerror(saved));
|
||||
}
|
||||
if (n > 0) (void) write(STDERR_FILENO, msg, (size_t) n);
|
||||
_exit(exit_code);
|
||||
}
|
||||
|
||||
static void xwrite_all(int fd, const char *buf, size_t len, const char *path) {
|
||||
size_t off = 0;
|
||||
while (off < len) {
|
||||
ssize_t n = write(fd, buf + off, len - off);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
die_perror("write failed", path, -1);
|
||||
}
|
||||
off += (size_t) n;
|
||||
}
|
||||
}
|
||||
|
||||
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 != 4) {
|
||||
const char *usage =
|
||||
"Usage: lab1_var_thirds_line <input.txt> <output.txt> <max_replacements>\n"
|
||||
"Replace every third non-newline byte in each line with a space; counter resets after LF.\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]);
|
||||
if (cap < 0) die_perror("invalid max_replacements", argv[3], -1);
|
||||
|
||||
int in_fd = open(in_path, O_RDONLY);
|
||||
if (in_fd < 0) die_perror("open input failed", in_path, -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("open output failed", out_path, -1);
|
||||
|
||||
char rbuf[RBUFSZ];
|
||||
char wbuf[WBUFSZ];
|
||||
size_t wlen = 0;
|
||||
|
||||
long long total = 0;
|
||||
long long col = 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 (c == '\n') {
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = '\n';
|
||||
col = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char outc = c;
|
||||
|
||||
col++;
|
||||
|
||||
if (replacing_enabled && (col % 3 == 0) && total < cap) {
|
||||
outc = ' ';
|
||||
total++;
|
||||
if (total == cap) replacing_enabled = 0;
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) outc;
|
||||
}
|
||||
} else if (n == 0) {
|
||||
if (wlen > 0) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
if (errno == EINTR) continue;
|
||||
die_perror("read failed", in_path, -1);
|
||||
}
|
||||
}
|
||||
|
||||
if (close(in_fd) < 0) die_perror("close input failed", in_path, -1);
|
||||
if (close(out_fd) < 0) die_perror("close output failed", out_path, -1);
|
||||
|
||||
char res[64];
|
||||
int m = snprintf(res, sizeof(res), "%lld\n", total);
|
||||
if (m > 0) (void) write(STDOUT_FILENO, res, (size_t) m);
|
||||
|
||||
return 0;
|
||||
}
|
||||
183
mine/lab_4/kirill's/fifo_server.c
Normal file
183
mine/lab_4/kirill's/fifo_server.c
Normal file
@@ -0,0 +1,183 @@
|
||||
// fifo_server.c - Серверная программа с использованием именованных каналов (FIFO)
|
||||
// Вариант повышенной сложности для Lab 4
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
|
||||
#define FIFO_REQUEST "/tmp/fifo_request"
|
||||
#define FIFO_RESPONSE "/tmp/fifo_response"
|
||||
#define BUFFER_SIZE 4096
|
||||
|
||||
volatile sig_atomic_t running = 1;
|
||||
|
||||
void signal_handler(int sig) {
|
||||
(void)sig;
|
||||
running = 0;
|
||||
}
|
||||
|
||||
static long long parse_ll(const char *s) {
|
||||
char *end = NULL;
|
||||
errno = 0;
|
||||
long long v = strtoll(s, &end, 10);
|
||||
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||
return -1;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
long long process_data(const char *input, size_t input_len, char *output,
|
||||
size_t output_size, long long max_replacements) {
|
||||
long long total_replacements = 0;
|
||||
long long col = 0; /* position in current line (counts non-newline bytes) */
|
||||
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 (c == '\n') {
|
||||
/* write newline, reset column counter */
|
||||
output[out_pos++] = '\n';
|
||||
col = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
col++;
|
||||
unsigned char outc = c;
|
||||
|
||||
if ((col % 3) == 0 && total_replacements < max_replacements) {
|
||||
outc = ' ';
|
||||
total_replacements++;
|
||||
}
|
||||
|
||||
output[out_pos++] = (char)outc;
|
||||
}
|
||||
|
||||
/* If there is space, terminate string */
|
||||
if (out_pos < output_size)
|
||||
output[out_pos] = '\0';
|
||||
else if (output_size > 0)
|
||||
output[output_size - 1] = '\0';
|
||||
|
||||
return total_replacements;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 2) {
|
||||
fprintf(stderr, "Usage: %s <max_replacements>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
long long max_replacements = parse_ll(argv[1]);
|
||||
if (max_replacements < 0) {
|
||||
fprintf(stderr, "ERROR: Invalid max_replacements\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("=== FIFO Server запущен ===\n");
|
||||
printf("Server PID: %d\n", getpid());
|
||||
printf("Максимум замен: %lld\n", max_replacements);
|
||||
|
||||
// Устанавливаем обработчик сигналов
|
||||
signal(SIGINT, signal_handler);
|
||||
signal(SIGTERM, signal_handler);
|
||||
|
||||
// Удаляем старые FIFO, если существуют
|
||||
unlink(FIFO_REQUEST);
|
||||
unlink(FIFO_RESPONSE);
|
||||
|
||||
// Создаем именованные каналы
|
||||
if (mkfifo(FIFO_REQUEST, 0666) == -1) {
|
||||
perror("mkfifo request");
|
||||
return 1;
|
||||
}
|
||||
if (mkfifo(FIFO_RESPONSE, 0666) == -1) {
|
||||
perror("mkfifo response");
|
||||
unlink(FIFO_REQUEST);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("FIFO каналы созданы:\n");
|
||||
printf(" Request: %s\n", FIFO_REQUEST);
|
||||
printf(" Response: %s\n", FIFO_RESPONSE);
|
||||
printf("Ожидание запросов от клиентов...\n\n");
|
||||
|
||||
while (running) {
|
||||
// Открываем FIFO для чтения запроса
|
||||
int fd_req = open(FIFO_REQUEST, O_RDONLY);
|
||||
if (fd_req == -1) {
|
||||
if (errno == EINTR) continue;
|
||||
perror("open request FIFO");
|
||||
break;
|
||||
}
|
||||
|
||||
// Читаем данные от клиента
|
||||
char *input_buffer = malloc(BUFFER_SIZE);
|
||||
char *output_buffer = malloc(BUFFER_SIZE);
|
||||
|
||||
if (!input_buffer || !output_buffer) {
|
||||
fprintf(stderr, "ERROR: Memory allocation failed\n");
|
||||
close(fd_req);
|
||||
free(input_buffer);
|
||||
free(output_buffer);
|
||||
continue;
|
||||
}
|
||||
|
||||
ssize_t bytes_read = read(fd_req, input_buffer, BUFFER_SIZE - 1);
|
||||
close(fd_req);
|
||||
|
||||
if (bytes_read <= 0) {
|
||||
free(input_buffer);
|
||||
free(output_buffer);
|
||||
continue;
|
||||
}
|
||||
|
||||
input_buffer[bytes_read] = '\0';
|
||||
printf("Получен запрос: %zd байт\n", bytes_read);
|
||||
|
||||
// Обрабатываем данные
|
||||
long long replacements = process_data(input_buffer, bytes_read,
|
||||
output_buffer, BUFFER_SIZE,
|
||||
max_replacements);
|
||||
|
||||
printf("Выполнено замен: %lld\n", replacements);
|
||||
|
||||
// Открываем FIFO для отправки ответа
|
||||
int fd_resp = open(FIFO_RESPONSE, O_WRONLY);
|
||||
if (fd_resp == -1) {
|
||||
perror("open response FIFO");
|
||||
free(input_buffer);
|
||||
free(output_buffer);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Отправляем обработанные данные
|
||||
size_t output_len = strlen(output_buffer);
|
||||
ssize_t bytes_written = write(fd_resp, output_buffer, output_len);
|
||||
|
||||
// Отправляем количество замен (в отдельной строке)
|
||||
char result[64];
|
||||
snprintf(result, sizeof(result), "\nREPLACEMENTS:%lld\n", replacements);
|
||||
write(fd_resp, result, strlen(result));
|
||||
|
||||
close(fd_resp);
|
||||
|
||||
printf("Отправлен ответ: %zd байт\n\n", bytes_written);
|
||||
|
||||
free(input_buffer);
|
||||
free(output_buffer);
|
||||
}
|
||||
|
||||
// Очистка
|
||||
printf("\nЗавершение работы сервера...\n");
|
||||
unlink(FIFO_REQUEST);
|
||||
unlink(FIFO_RESPONSE);
|
||||
|
||||
return 0;
|
||||
}
|
||||
99
mine/lab_4/vlad's/Makefile
Normal file
99
mine/lab_4/vlad's/Makefile
Normal file
@@ -0,0 +1,99 @@
|
||||
# Makefile for lab 4 - FIFO (named pipes) only
|
||||
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||
|
||||
# Default target - build FIFO programs
|
||||
all: fifo
|
||||
|
||||
# ===== FIFO targets =====
|
||||
fifo: fifo_server fifo_client
|
||||
|
||||
fifo_server: fifo_server.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
fifo_client: fifo_client.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
# ===== Test files =====
|
||||
test_files:
|
||||
@echo "Создание тестовых файлов..."
|
||||
echo "abbaabbaabbaabbaabbaabbaabbaabba" > input1.txt
|
||||
echo "xyzxyzxyzxyzxyzxyzxyzxyz" >> input1.txt
|
||||
echo "hello world hello" >> input1.txt
|
||||
echo "testtest" > input2.txt
|
||||
echo "aaaaaaa" >> input2.txt
|
||||
echo "programming" > input3.txt
|
||||
echo "ppppython" >> input3.txt
|
||||
|
||||
# ===== FIFO tests =====
|
||||
test_fifo_server: fifo test_files
|
||||
@echo "=== Запуск FIFO сервера ==="
|
||||
@echo "В другом терминале выполните: make test_fifo_client"
|
||||
./fifo_server 10
|
||||
|
||||
test_fifo_client: fifo test_files
|
||||
@echo "=== Запуск FIFO клиента ===" & \
|
||||
./fifo_client input1.txt output1_fifo.txt; \
|
||||
./fifo_client input2.txt output2_fifo.txt; \
|
||||
./fifo_client input3.txt output3_fifo.txt;
|
||||
@echo "\n=== Результаты FIFO ==="
|
||||
@echo "--- output1_fifo.txt ---"
|
||||
@cat output1_fifo.txt || true
|
||||
@echo "\n--- output2_fifo.txt ---"
|
||||
@cat output2_fifo.txt || true
|
||||
@echo "\n--- output3_fifo.txt ---"
|
||||
@cat output3_fifo.txt || true
|
||||
|
||||
# Automatic FIFO test (server in background)
|
||||
test_all: fifo test_files
|
||||
@echo "=== Автоматический тест FIFO ==="
|
||||
@./fifo_server 10 & \
|
||||
SERVER_PID=$$!; \
|
||||
sleep 1; \
|
||||
./fifo_client input1.txt output1_fifo.txt; \
|
||||
./fifo_client input2.txt output2_fifo.txt; \
|
||||
./fifo_client input3.txt output3_fifo.txt; \
|
||||
kill $$SERVER_PID 2>/dev/null || true; \
|
||||
wait $$SERVER_PID 2>/dev/null || true
|
||||
@echo "\n=== Результаты FIFO ==="
|
||||
@echo "--- output1_fifo.txt ---"
|
||||
@cat output1_fifo.txt || true
|
||||
@echo "\n--- output2_fifo.txt ---"
|
||||
@cat output2_fifo.txt || true
|
||||
@echo "\n--- output3_fifo.txt ---"
|
||||
@cat output3_fifo.txt || true
|
||||
|
||||
# Error handling test for FIFO
|
||||
test_error: fifo
|
||||
@echo "\n=== Тест обработки ошибки (несуществующий файл) - FIFO ==="
|
||||
@./fifo_server 5 & \
|
||||
SERVER_PID=$$!; \
|
||||
sleep 1; \
|
||||
./fifo_client nonexistent.txt output_error.txt || true; \
|
||||
kill $$SERVER_PID 2>/dev/null || true; \
|
||||
wait $$SERVER_PID 2>/dev/null || true
|
||||
|
||||
# Cleanup
|
||||
clean:
|
||||
@echo "Очистка..."
|
||||
rm -f fifo_server fifo_client
|
||||
rm -f input1.txt input2.txt input3.txt
|
||||
rm -f output*.txt
|
||||
rm -f /tmp/fifo_request /tmp/fifo_response
|
||||
|
||||
# Help
|
||||
help:
|
||||
@echo "Доступные цели:"
|
||||
@echo " all - Скомпилировать FIFO программы"
|
||||
@echo " fifo - Скомпилировать fifo_server и fifo_client"
|
||||
@echo " test_files - Создать тестовые входные файлы"
|
||||
@echo " test_fifo_server - Запустить FIFO сервер (использовать с клиентом в другом терминале)"
|
||||
@echo " test_fifo_client - Запустить FIFO клиент и показать результат"
|
||||
@echo " test_fifo_auto - Автоматический тест FIFO (сервер в фоне)"
|
||||
@echo " test_all - Запустить все тесты (FIFO)"
|
||||
@echo " test_error_fifo - Тест обработки ошибок (несуществующий файл)"
|
||||
@echo " clean - Удалить скомпилированные файлы и тесты"
|
||||
|
||||
.PHONY: all fifo test_files test_fifo_server test_fifo_client test_all \
|
||||
test_error clean help
|
||||
144
mine/lab_4/vlad's/fifo_client.c
Normal file
144
mine/lab_4/vlad's/fifo_client.c
Normal file
@@ -0,0 +1,144 @@
|
||||
// fifo_client.c - Клиентская программа с использованием именованных каналов (FIFO)
|
||||
|
||||
#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);
|
||||
|
||||
// Открываем FIFO для отправки запроса
|
||||
printf("Отправка запроса серверу...\n");
|
||||
int fd_req = open(FIFO_REQUEST, O_WRONLY);
|
||||
if (fd_req == -1) {
|
||||
fprintf(stderr, "ERROR: Не удалось открыть FIFO запроса: %s\n", strerror(errno));
|
||||
fprintf(stderr, "Убедитесь, что сервер запущен!\n");
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Отправляем данные серверу
|
||||
ssize_t bytes_written = write(fd_req, buffer, bytes_read);
|
||||
close(fd_req);
|
||||
|
||||
if (bytes_written != bytes_read) {
|
||||
fprintf(stderr, "ERROR: Ошибка отправки данных\n");
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Отправлено байт: %zd\n", bytes_written);
|
||||
|
||||
// Открываем FIFO для получения ответа
|
||||
printf("Ожидание ответа от сервера...\n");
|
||||
int fd_resp = open(FIFO_RESPONSE, O_RDONLY);
|
||||
if (fd_resp == -1) {
|
||||
fprintf(stderr, "ERROR: Не удалось открыть FIFO ответа: %s\n", strerror(errno));
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Читаем обработанные данные
|
||||
ssize_t response_bytes = read(fd_resp, buffer, BUFFER_SIZE - 1);
|
||||
close(fd_resp);
|
||||
|
||||
if (response_bytes < 0) {
|
||||
fprintf(stderr, "ERROR: Ошибка чтения ответа\n");
|
||||
free(buffer);
|
||||
return 1;
|
||||
}
|
||||
|
||||
buffer[response_bytes] = '\0';
|
||||
printf("Получено байт от сервера: %zd\n", response_bytes);
|
||||
|
||||
// Ищем информацию о количестве замен
|
||||
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;
|
||||
}
|
||||
141
mine/lab_6/kirill/client.c
Normal file
141
mine/lab_6/kirill/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;
|
||||
}
|
||||
185
mine/lab_6/kirill/server.c
Normal file
185
mine/lab_6/kirill/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;
|
||||
}
|
||||
51
mine/lab_6/vlad/Makefile
Normal file
51
mine/lab_6/vlad/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
|
||||
6
mine/lab_6/vlad/input.txt
Normal file
6
mine/lab_6/vlad/input.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
abacaba
|
||||
xxxxxx
|
||||
hello
|
||||
aaaaa
|
||||
1abc1d1e1
|
||||
qwerty
|
||||
43
mine/lab_7/kirill/Makefile
Normal file
43
mine/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
mine/lab_7/kirill/main.c
Normal file
276
mine/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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user