diff --git a/lab_3/Makefile b/lab_3/Makefile new file mode 100644 index 0000000..5f66809 --- /dev/null +++ b/lab_3/Makefile @@ -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 \ No newline at end of file diff --git a/lab_3/README-lab3.md b/lab_3/README-lab3.md new file mode 100644 index 0000000..ea73e79 --- /dev/null +++ b/lab_3/README-lab3.md @@ -0,0 +1,231 @@ +# Инструкция по сборке и запуску + +## Лабораторная работа №3: Многозадачное программирование в Linux + +### Описание задания +Программа запускает программу из лабораторной работы №1 в нескольких дочерних процессах для обработки множества входных файлов параллельно. + +**Вариант 12**: Замена первого символа каждой строки на пробелы (до достижения лимита замен). + +--- + +## Структура проекта + +``` +lab3/ +├── parent.c # Родительская программа (многозадачная) +├── lab1_var12.c # Программа из лабораторной работы №1 +├── Makefile # Makefile для сборки +└── README.md # Эта инструкция +``` + +--- + +## Сборка проекта + +### 1. Компиляция всех программ +```bash +make +``` + +Будут созданы: +- `parent` — родительская программа +- `lab1_var12` — программа обработки текста из лабы №1 + +### 2. Сборка отдельных программ +```bash +make parent # только родительская программа +make lab1_var12 # только программа из лабы №1 +``` + +--- + +## Использование + +### Формат запуска +```bash +./parent <программа> <вход1> <выход1> [<вход2> <выход2> ...] +``` + +**Параметры:** +- `<программа>` — путь к программе lab1_var12 +- `` — максимальное количество замен символов +- `<вход1>` `<выход1>` — пары входной/выходной файл (можно несколько) + +### Пример 1: Обработка трёх файлов +```bash +./parent ./lab1_var12 10 input1.txt output1.txt input2.txt output2.txt input3.txt output3.txt +``` + +### Пример 2: Обработка одного файла +```bash +./parent ./lab1_var12 5 test.txt result.txt +``` + +--- + +## Автоматические тесты + +### Базовый тест (создание тестовых файлов и запуск) +```bash +make test +``` +Создаёт три тестовых входных файла, запускает обработку и показывает результаты. + +### Тест обработки ошибок: несуществующий входной файл +```bash +make test_error +``` + +### Тест обработки ошибок: неверная программа +```bash +make test_bad_program +``` + +### Тест обработки ошибок: неверные аргументы +```bash +make test_bad_args +``` + +--- + +## Примеры работы программы + +### Успешное выполнение + +``` +$ ./parent ./lab1_var12 10 input1.txt output1.txt input2.txt output2.txt + +=== Запуск родительского процесса === +Родительский PID: 12345 +Программа для запуска: ./lab1_var12 +Максимум замен: 10 +Количество файловых пар: 2 + +Создание процесса 1 для файлов: input1.txt -> output1.txt + -> Дочерний процесс PID=12346 запускает обработку input1.txt +Создание процесса 2 для файлов: input2.txt -> output2.txt + -> Дочерний процесс PID=12347 запускает обработку input2.txt + +=== Ожидание завершения дочерних процессов === + +Процесс PID=12346 завершен (input1.txt -> output1.txt) + Код завершения: 0 + Статус: SUCCESS + +Процесс PID=12347 завершен (input2.txt -> output2.txt) + Код завершения: 0 + Статус: SUCCESS + +=== Итоговая статистика === +Всего запущено процессов: 2 +Успешно завершено: 2 +Завершено с ошибкой: 0 + +ОБЩИЙ СТАТУС: Все процессы завершены успешно +``` + +### Обработка ошибок + +#### 1. Недостаточно аргументов +``` +$ ./parent ./lab1_var12 5 + +ERROR: Недостаточное или неверное количество аргументов +Usage: ./parent [ ...] +Example: ./parent ./lab1_var12 5 in1.txt out1.txt in2.txt out2.txt +``` + +#### 2. Несуществующий входной файл +``` +$ ./parent ./lab1_var12 5 nonexistent.txt output.txt + +=== Запуск родительского процесса === +... +Создание процесса 1 для файлов: nonexistent.txt -> output.txt + -> Дочерний процесс PID=12351 запускает обработку nonexistent.txt +open input failed: nonexistent.txt: No such file or directory + +Процесс PID=12351 завершен (nonexistent.txt -> output.txt) + Код завершения: 255 + Статус: ERROR (не удалось выполнить) + +=== Итоговая статистика === +Всего запущено процессов: 1 +Успешно завершено: 0 +Завершено с ошибкой: 1 + +ОБЩИЙ СТАТУС: Завершено с ошибками +``` + +#### 3. Невозможность запустить программу +``` +$ ./parent ./nonexistent_program 5 input.txt output.txt + +=== Запуск родительского процесса === +... +ERROR: Не удалось запустить программу ./nonexistent_program: No such file or directory + +Процесс PID=12355 завершен (input.txt -> output.txt) + Код завершения: 255 + Статус: ERROR (не удалось выполнить) +``` + +--- + +## Функциональность родительской программы + +### Основные возможности: +1. **Создание дочерних процессов** — используется `fork()` +2. **Запуск программы в дочернем процессе** — используется `execl()` +3. **Ожидание завершения процессов** — используется `waitpid()` +4. **Получение кодов завершения** — макросы `WIFEXITED()`, `WEXITSTATUS()`, `WIFSIGNALED()` +5. **Обработка исключительных ситуаций**: + - Недостаточное количество аргументов + - Невозможность создать процесс (fork failed) + - Невозможность запустить программу (exec failed) + - Ошибки при обработке файлов + +### Коды завершения: +- **0** — успешное выполнение +- **-1 (255)** — ошибка (невозможно открыть файл, неверные аргументы и т.д.) +- **Другие коды** — различные ошибки + +--- + +## Очистка + +```bash +make clean +``` + +Удалит: +- Исполняемые файлы (`parent`, `lab1_var12`) +- Все тестовые входные/выходные файлы + +--- + +## Технические детали + +### Системные вызовы: +- `fork()` — создание дочернего процесса +- `execl()` — запуск программы в дочернем процессе +- `waitpid()` — ожидание завершения дочернего процесса +- `getpid()` — получение PID текущего процесса + +### Обработка статусов: +- `WIFEXITED(status)` — процесс завершился нормально +- `WEXITSTATUS(status)` — код завершения процесса +- `WIFSIGNALED(status)` — процесс завершён сигналом +- `WTERMSIG(status)` — номер сигнала + +### Компилятор: +- GCC версии 4.0 или выше +- Флаги: `-Wall -Wextra -std=c99 -g` + +--- + +## Автор +Лабораторная работа №3 +Системное программирование в Linux +Вариант 12 \ No newline at end of file diff --git a/lab_3/demo_output.txt b/lab_3/demo_output.txt new file mode 100644 index 0000000..ad3f62b --- /dev/null +++ b/lab_3/demo_output.txt @@ -0,0 +1,91 @@ + +=== ПРИМЕР ВЫВОДА ПРОГРАММЫ === + +$ make test + +=== Запуск теста с тремя файлами === +./parent ./lab1_var12 10 input1.txt output1.txt input2.txt output2.txt input3.txt output3.txt + +=== Запуск родительского процесса === +Родительский PID: 12345 +Программа для запуска: ./lab1_var12 +Максимум замен: 10 +Количество файловых пар: 3 + +Создание процесса 1 для файлов: input1.txt -> output1.txt + -> Дочерний процесс PID=12346 запускает обработку input1.txt +Создание процесса 2 для файлов: input2.txt -> output2.txt + -> Дочерний процесс PID=12347 запускает обработку input2.txt +Создание процесса 3 для файлов: input3.txt -> output3.txt + -> Дочерний процесс PID=12348 запускает обработку input3.txt + +=== Ожидание завершения дочерних процессов === + +Процесс PID=12346 завершен (input1.txt -> output1.txt) + Код завершения: 0 + Статус: SUCCESS + +Процесс PID=12347 завершен (input2.txt -> output2.txt) + Код завершения: 0 + Статус: SUCCESS + +Процесс PID=12348 завершен (input3.txt -> output3.txt) + Код завершения: 0 + Статус: SUCCESS + +=== Итоговая статистика === +Всего запущено процессов: 3 +Успешно завершено: 3 +Завершено с ошибкой: 0 + +ОБЩИЙ СТАТУС: Все процессы завершены успешно + +=== Результаты обработки === +--- output1.txt --- + bb bb bb bbaabbaabbaabbaabba +xyzxyzxyzxyzxyzxyzxyzxyz +hello world hello + +--- output2.txt --- +testtest +aaaaaaa + +--- output3.txt --- +programming +ppppython + +========================================== +=== ПРИМЕР ОБРАБОТКИ ОШИБОК === + +$ ./parent ./lab1_var12 5 + +ERROR: Недостаточное или неверное количество аргументов +Usage: ./parent [ ...] +Example: ./parent ./lab1_var12 5 in1.txt out1.txt in2.txt out2.txt + +========================================== + +$ ./parent ./lab1_var12 5 nonexistent.txt output.txt + +=== Запуск родительского процесса === +Родительский PID: 12350 +Программа для запуска: ./lab1_var12 +Максимум замен: 5 +Количество файловых пар: 1 + +Создание процесса 1 для файлов: nonexistent.txt -> output.txt + -> Дочерний процесс PID=12351 запускает обработку nonexistent.txt +open input failed: nonexistent.txt: No such file or directory + +=== Ожидание завершения дочерних процессов === + +Процесс PID=12351 завершен (nonexistent.txt -> output.txt) + Код завершения: 255 + Статус: ERROR (не удалось выполнить) + +=== Итоговая статистика === +Всего запущено процессов: 1 +Успешно завершено: 0 +Завершено с ошибкой: 1 + +ОБЩИЙ СТАТУС: Завершено с ошибками diff --git a/lab_3/lab1_var12.c b/lab_3/lab1_var12.c new file mode 100644 index 0000000..38b5f46 --- /dev/null +++ b/lab_3/lab1_var12.c @@ -0,0 +1,137 @@ +// lab1_var12.c - Программа из лабораторной работы №1 +// Вариант 12: замена символа первого в строке на пробелы +#include +#include +#include +#include +#include +#include +#include + +#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 \n" + "Variant 12: per line, take the first character as key and replace its matches with spaces,\n" + " stopping after 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; +} \ No newline at end of file diff --git a/lab_3/parent.c b/lab_3/parent.c new file mode 100644 index 0000000..3bad511 --- /dev/null +++ b/lab_3/parent.c @@ -0,0 +1,156 @@ +// parent.c - Родительская программа для лабораторной работы №3 +// Запускает программу lab1_var12 в нескольких дочерних процессах +#include +#include +#include +#include +#include +#include +#include + +#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 [ ...]\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 <программа> [ ...] + 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; + } +} \ No newline at end of file