accidental rollback
This commit is contained in:
55
lab_3/kirill/Makefile
Normal file
55
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
lab_3/kirill/parent.c
Normal file
117
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
lab_3/kirill/task18.c
Normal file
129
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;
|
||||
}
|
||||
Reference in New Issue
Block a user