kirill-refactor
This commit is contained in:
62
mine/lab_3/Makefile
Normal file
62
mine/lab_3/Makefile
Normal file
@@ -0,0 +1,62 @@
|
||||
# Makefile для лабораторной работы №3
|
||||
# Многозадачное программирование
|
||||
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -std=c99 -g
|
||||
|
||||
# Цель по умолчанию
|
||||
all: parent lab1_var12
|
||||
|
||||
# Родительская программа
|
||||
parent: parent.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
# Программа из лабораторной работы №1
|
||||
lab1_var12: lab1_var12.c
|
||||
$(CC) $(CFLAGS) -o $@ $<
|
||||
|
||||
# Создание тестовых файлов
|
||||
test_files:
|
||||
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
|
||||
|
||||
# Тест с несколькими файлами
|
||||
test: all test_files
|
||||
@echo "=== Запуск теста с тремя файлами ==="
|
||||
./parent ./lab1_var12 10 input1.txt output1.txt input2.txt output2.txt input3.txt output3.txt
|
||||
@echo ""
|
||||
@echo "=== Результаты обработки ==="
|
||||
@echo "--- output1.txt ---"
|
||||
@cat output1.txt
|
||||
@echo "--- output2.txt ---"
|
||||
@cat output2.txt
|
||||
@echo "--- output3.txt ---"
|
||||
@cat output3.txt
|
||||
|
||||
# Тест обработки ошибок - несуществующий файл
|
||||
test_error: all
|
||||
@echo "=== Тест обработки ошибки (несуществующий входной файл) ==="
|
||||
./parent ./lab1_var12 5 nonexistent.txt output_error.txt
|
||||
|
||||
# Тест обработки ошибок - неверная программа
|
||||
test_bad_program: all test_files
|
||||
@echo "=== Тест обработки ошибки (неверная программа) ==="
|
||||
./parent ./nonexistent_program 5 input1.txt output1.txt
|
||||
|
||||
# Тест обработки ошибок - недостаточно аргументов
|
||||
test_bad_args: all
|
||||
@echo "=== Тест обработки ошибки (недостаточно аргументов) ==="
|
||||
./parent ./lab1_var12 5
|
||||
|
||||
# Очистка
|
||||
clean:
|
||||
rm -f parent lab1_var12
|
||||
rm -f input1.txt input2.txt input3.txt
|
||||
rm -f output1.txt output2.txt output3.txt output_error.txt
|
||||
|
||||
.PHONY: all test test_files test_error test_bad_program test_bad_args clean
|
||||
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;
|
||||
}
|
||||
137
mine/lab_3/lab1_var12.c
Normal file
137
mine/lab_3/lab1_var12.c
Normal file
@@ -0,0 +1,137 @@
|
||||
// lab1_var12.c - Программа из лабораторной работы №1
|
||||
// Вариант 12: замена символа первого в строке на пробелы
|
||||
#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];
|
||||
if (path) {
|
||||
snprintf(msg, sizeof(msg), "%s: %s: %s\n", what, path, strerror(saved));
|
||||
} else {
|
||||
snprintf(msg, sizeof(msg), "%s: %s\n", what, strerror(saved));
|
||||
}
|
||||
(void) write(STDERR_FILENO, msg, strlen(msg));
|
||||
_exit(exit_code);
|
||||
}
|
||||
|
||||
static long long parse_ll(const char *s) {
|
||||
char *end = NULL;
|
||||
errno = 0;
|
||||
long long v = strtoll(s, &end, 10);
|
||||
if (errno != 0 || end == s || *end != '\0' || v < 0) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 4) {
|
||||
const char *usage =
|
||||
"Usage: lab1_var12 <input.txt> <output.txt> <max_replacements>\n"
|
||||
"Variant 12: per line, take the first character as key and replace its matches with spaces,\n"
|
||||
" stopping after <max_replacements> replacements globally.\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 filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* rw-rw-rw- */
|
||||
int out_fd = open(out_path, O_CREAT | O_WRONLY | O_TRUNC, filePerms);
|
||||
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_replacements = 0;
|
||||
int at_line_start = 1;
|
||||
unsigned char line_key = 0;
|
||||
int replacing_enabled = 1; /* flips to 0 when cap reached */
|
||||
|
||||
for (;;) {
|
||||
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
||||
if (n > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char) rbuf[i];
|
||||
|
||||
if (at_line_start) {
|
||||
line_key = c;
|
||||
at_line_start = 0;
|
||||
}
|
||||
|
||||
unsigned char outc = c;
|
||||
if (c == '\n') {
|
||||
at_line_start = 1;
|
||||
} else if (replacing_enabled && c == line_key) {
|
||||
if (total_replacements < cap) {
|
||||
outc = ' ';
|
||||
total_replacements++;
|
||||
if (total_replacements == cap) {
|
||||
replacing_enabled = 0; /* hit the cap; from now on just copy */
|
||||
}
|
||||
} else {
|
||||
replacing_enabled = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
ssize_t wrote = write(out_fd, wbuf, wlen);
|
||||
if (wrote < 0 || (size_t) wrote != wlen) {
|
||||
die_perror("write failed", out_path, -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("write failed", out_path, -1);
|
||||
}
|
||||
wlen = 0;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
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_replacements);
|
||||
if (m > 0) {
|
||||
(void) write(STDOUT_FILENO, res, (size_t) m);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
156
mine/lab_3/parent.c
Normal file
156
mine/lab_3/parent.c
Normal file
@@ -0,0 +1,156 @@
|
||||
// parent.c - Родительская программа для лабораторной работы №3
|
||||
// Запускает программу lab1_var12 в нескольких дочерних процессах
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
#define MAX_PROCESSES 100
|
||||
|
||||
// Структура для хранения информации о дочернем процессе
|
||||
typedef struct {
|
||||
pid_t pid;
|
||||
char *input_file;
|
||||
char *output_file;
|
||||
} ChildInfo;
|
||||
|
||||
void print_usage(const char *progname) {
|
||||
fprintf(stderr, "Usage: %s <lab1_program> <max_replacements> <input1> <output1> [<input2> <output2> ...]\n", progname);
|
||||
fprintf(stderr, "Example: %s ./lab1_var12 5 in1.txt out1.txt in2.txt out2.txt\n", progname);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// Проверка минимального количества аргументов
|
||||
// Формат: parent <программа> <max_repl> <input1> <output1> [<input2> <output2> ...]
|
||||
if (argc < 5 || (argc - 3) % 2 != 0) {
|
||||
fprintf(stderr, "ERROR: Недостаточное или неверное количество аргументов\n");
|
||||
print_usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *lab1_program = argv[1];
|
||||
const char *max_replacements = argv[2];
|
||||
|
||||
// Вычисляем количество пар (input, output)
|
||||
int num_files = (argc - 3) / 2;
|
||||
|
||||
if (num_files > MAX_PROCESSES) {
|
||||
fprintf(stderr, "ERROR: Слишком много файлов (максимум %d пар)\n", MAX_PROCESSES);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("=== Запуск родительского процесса ===\n");
|
||||
printf("Родительский PID: %d\n", getpid());
|
||||
printf("Программа для запуска: %s\n", lab1_program);
|
||||
printf("Максимум замен: %s\n", max_replacements);
|
||||
printf("Количество файловых пар: %d\n\n", num_files);
|
||||
|
||||
// Массив для хранения информации о дочерних процессах
|
||||
ChildInfo children[MAX_PROCESSES];
|
||||
int created_count = 0;
|
||||
|
||||
// Создаем дочерние процессы
|
||||
for (int i = 0; i < num_files; i++) {
|
||||
char *input_file = argv[3 + i * 2];
|
||||
char *output_file = argv[3 + i * 2 + 1];
|
||||
|
||||
printf("Создание процесса %d для файлов: %s -> %s\n", i + 1, input_file, output_file);
|
||||
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid < 0) {
|
||||
// Ошибка при создании процесса
|
||||
fprintf(stderr, "ERROR: Не удалось создать дочерний процесс для %s: %s\n",
|
||||
input_file, strerror(errno));
|
||||
continue; // Продолжаем создавать остальные процессы
|
||||
}
|
||||
else if (pid == 0) {
|
||||
// Дочерний процесс
|
||||
printf(" -> Дочерний процесс PID=%d запускает обработку %s\n",
|
||||
getpid(), input_file);
|
||||
|
||||
// Запускаем программу lab1_var12 с аргументами
|
||||
execl(lab1_program, lab1_program, input_file, output_file, max_replacements, NULL);
|
||||
|
||||
// Если execl вернул управление, значит произошла ошибка
|
||||
fprintf(stderr, "ERROR: Не удалось запустить программу %s: %s\n",
|
||||
lab1_program, strerror(errno));
|
||||
_exit(-1);
|
||||
}
|
||||
else {
|
||||
// Родительский процесс
|
||||
children[created_count].pid = pid;
|
||||
children[created_count].input_file = input_file;
|
||||
children[created_count].output_file = output_file;
|
||||
created_count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (created_count == 0) {
|
||||
fprintf(stderr, "ERROR: Ни один дочерний процесс не был создан\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("\n=== Ожидание завершения дочерних процессов ===\n");
|
||||
|
||||
// Ожидаем завершения всех дочерних процессов
|
||||
int success_count = 0;
|
||||
int error_count = 0;
|
||||
|
||||
for (int i = 0; i < created_count; i++) {
|
||||
int status;
|
||||
pid_t finished_pid = waitpid(children[i].pid, &status, 0);
|
||||
|
||||
if (finished_pid < 0) {
|
||||
fprintf(stderr, "ERROR: Ошибка при ожидании процесса PID=%d: %s\n",
|
||||
children[i].pid, strerror(errno));
|
||||
error_count++;
|
||||
continue;
|
||||
}
|
||||
|
||||
printf("\nПроцесс PID=%d завершен (%s -> %s)\n",
|
||||
finished_pid, children[i].input_file, children[i].output_file);
|
||||
|
||||
if (WIFEXITED(status)) {
|
||||
int exit_code = WEXITSTATUS(status);
|
||||
printf(" Код завершения: %d\n", exit_code);
|
||||
|
||||
if (exit_code == 0) {
|
||||
printf(" Статус: SUCCESS\n");
|
||||
success_count++;
|
||||
} else if (exit_code == 255 || exit_code == -1) {
|
||||
printf(" Статус: ERROR (не удалось выполнить)\n");
|
||||
error_count++;
|
||||
} else {
|
||||
printf(" Статус: ERROR\n");
|
||||
error_count++;
|
||||
}
|
||||
}
|
||||
else if (WIFSIGNALED(status)) {
|
||||
int signal = WTERMSIG(status);
|
||||
printf(" Процесс завершен сигналом: %d\n", signal);
|
||||
printf(" Статус: ERROR (получен сигнал)\n");
|
||||
error_count++;
|
||||
}
|
||||
else {
|
||||
printf(" Статус: Неизвестный статус завершения\n");
|
||||
error_count++;
|
||||
}
|
||||
}
|
||||
|
||||
printf("\n=== Итоговая статистика ===\n");
|
||||
printf("Всего запущено процессов: %d\n", created_count);
|
||||
printf("Успешно завершено: %d\n", success_count);
|
||||
printf("Завершено с ошибкой: %d\n", error_count);
|
||||
|
||||
if (error_count > 0) {
|
||||
printf("\nОБЩИЙ СТАТУС: Завершено с ошибками\n");
|
||||
return 1;
|
||||
} else {
|
||||
printf("\nОБЩИЙ СТАТУС: Все процессы завершены успешно\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
51
mine/lab_3/vlad/Makefile
Normal file
51
mine/lab_3/vlad/Makefile
Normal file
@@ -0,0 +1,51 @@
|
||||
# Компилятор и флаги
|
||||
CC = gcc
|
||||
CFLAGS = -Wall -Wextra -std=c99 -pedantic
|
||||
|
||||
# Целевые файлы
|
||||
TARGET_PARENT = parent
|
||||
TARGET_TASK11 = task11
|
||||
|
||||
# Исходные файлы
|
||||
SRC_PARENT = parent.c
|
||||
SRC_TASK11 = task11.c
|
||||
|
||||
# Объектные файлы
|
||||
OBJ_PARENT = $(SRC_PARENT:.c=.o)
|
||||
OBJ_TASK11 = $(SRC_TASK11:.c=.o)
|
||||
|
||||
.PHONY: all clean help test
|
||||
|
||||
all: $(TARGET_PARENT) $(TARGET_TASK11)
|
||||
|
||||
$(TARGET_PARENT): $(OBJ_PARENT)
|
||||
$(CC) $(CFLAGS) -o $@ $^
|
||||
@echo "Родительская программа собрана: $@"
|
||||
|
||||
$(TARGET_TASK11): $(OBJ_TASK11)
|
||||
$(CC) $(CFLAGS) -o $@ $^
|
||||
@echo "Программа лаб. работы №11 собрана: $@"
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET_PARENT) $(TARGET_TASK11) $(OBJ_PARENT) $(OBJ_TASK11) input* output*
|
||||
@echo "Очистка завершена"
|
||||
|
||||
help:
|
||||
@echo "Доступные цели:"
|
||||
@echo " all - собрать все"
|
||||
@echo " clean - удалить все скомпилированные файлы"
|
||||
@echo " test - запустить тестирование программы"
|
||||
|
||||
test: all
|
||||
@echo "Создаем тестовые файлы..."
|
||||
@echo "abbaabbccdd" > input1.txt
|
||||
@echo "hello world !!" > 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 не найден"
|
||||
88
mine/lab_3/vlad/parent.c
Normal file
88
mine/lab_3/vlad/parent.c
Normal file
@@ -0,0 +1,88 @@
|
||||
#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) {
|
||||
fprintf(stderr,
|
||||
"Usage: parent <max_replacements> <input1.txt> <output1.txt> [<input2.txt> <output2.txt> ...]\n"
|
||||
" max_replacements: maximum number of replacements\n"
|
||||
" input/output: pairs of input and output files\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((argc - 2) % 2 != 0) {
|
||||
fprintf(stderr, "Error: number of input/output files must be even (pairs of input/output)\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *max_replacements_arg = argv[1];
|
||||
int num_pairs = (argc - 2) / 2;
|
||||
|
||||
pid_t *child_pids = malloc(num_pairs * sizeof(pid_t));
|
||||
if (!child_pids) {
|
||||
perror("malloc failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < num_pairs; 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");
|
||||
// Wait for already started children
|
||||
for (int j = 0; j < i; j++) {
|
||||
waitpid(child_pids[j], NULL, 0);
|
||||
}
|
||||
free(child_pids);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
// Child process
|
||||
printf("Child %d (PID=%d) processing %s -> %s\n", i + 1, getpid(), input_file, output_file);
|
||||
execl("./task11", "task11", input_file, output_file, max_replacements_arg, (char *) NULL);
|
||||
|
||||
// If exec returns, error happened
|
||||
fprintf(stderr, "Child %d: execl failed for %s: %s\n", i + 1, input_file, strerror(errno));
|
||||
_exit(-1);
|
||||
}
|
||||
|
||||
// Parent process
|
||||
child_pids[i] = pid;
|
||||
}
|
||||
|
||||
printf("Parent process waiting for children...\n");
|
||||
|
||||
int ret_code = 0;
|
||||
for (int i = 0; i < num_pairs; i++) {
|
||||
int status;
|
||||
pid_t pid = waitpid(child_pids[i], &status, 0);
|
||||
if (pid < 0) {
|
||||
perror("waitpid failed");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (WIFEXITED(status)) {
|
||||
int code = WEXITSTATUS(status);
|
||||
printf("Child %d (PID=%d) exited with code %d\n", i + 1, pid, code);
|
||||
if (code != 0) {
|
||||
ret_code = code;
|
||||
}
|
||||
} else if (WIFSIGNALED(status)) {
|
||||
printf("Child %d (PID=%d) terminated by signal %d\n", i + 1, pid, WTERMSIG(status));
|
||||
} else {
|
||||
printf("Child %d (PID=%d) ended abnormally\n", i + 1, pid);
|
||||
}
|
||||
}
|
||||
|
||||
free(child_pids);
|
||||
printf("All children finished\n");
|
||||
return ret_code;
|
||||
}
|
||||
170
mine/lab_3/vlad/task11.c
Normal file
170
mine/lab_3/vlad/task11.c
Normal file
@@ -0,0 +1,170 @@
|
||||
#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 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 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;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 4) {
|
||||
const char *usage =
|
||||
"Usage: lab1_var11 <input.txt> <output.txt> <max_replacements>\n"
|
||||
"Variant 11: for every pair of identical consecutive characters, replace the second with a space.\n"
|
||||
" Stop after <max_replacements> replacements globally.\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 filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
|
||||
int out_fd = open(out_path, O_CREAT | O_WRONLY | O_TRUNC, filePerms);
|
||||
if (out_fd < 0) {
|
||||
die_perror("open output failed", out_path, -1);
|
||||
}
|
||||
|
||||
char rbuf[RBUFSZ];
|
||||
char wbuf[WBUFSZ];
|
||||
size_t wlen = 0;
|
||||
|
||||
long long total_replacements = 0;
|
||||
int replacing_enabled = 1;
|
||||
|
||||
int have_prev = 0;
|
||||
unsigned char prev = 0;
|
||||
|
||||
for (;;) {
|
||||
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
|
||||
if (n > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char) rbuf[i];
|
||||
|
||||
if (!have_prev) {
|
||||
prev = c;
|
||||
have_prev = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == prev) {
|
||||
unsigned char out1 = prev;
|
||||
unsigned char out2 = c;
|
||||
|
||||
if (replacing_enabled && total_replacements < cap) {
|
||||
out2 = ' ';
|
||||
total_replacements++;
|
||||
if (total_replacements == cap) {
|
||||
replacing_enabled = 0;
|
||||
}
|
||||
} else {
|
||||
replacing_enabled = 0;
|
||||
}
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) out1;
|
||||
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) out2;
|
||||
|
||||
have_prev = 0;
|
||||
} else {
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) prev;
|
||||
|
||||
prev = c;
|
||||
have_prev = 1;
|
||||
}
|
||||
}
|
||||
} else if (n == 0) {
|
||||
if (have_prev) {
|
||||
if (wlen == sizeof(wbuf)) {
|
||||
xwrite_all(out_fd, wbuf, wlen, out_path);
|
||||
wlen = 0;
|
||||
}
|
||||
wbuf[wlen++] = (char) prev;
|
||||
have_prev = 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_replacements);
|
||||
if (m > 0) {
|
||||
(void) write(STDOUT_FILENO, res, (size_t) m);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user