This commit is contained in:
2025-12-11 10:17:13 +07:00
parent 8a15b8d0f8
commit 82dd7bf77f
29 changed files with 0 additions and 2416 deletions

View File

@@ -1,4 +0,0 @@
123456123456123456123456123456123456123456123456
123456123456
123456123456
123456123456

View File

@@ -1,129 +0,0 @@
#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;
}

View File

@@ -1,8 +0,0 @@
aaaaaa
aaaaaaaaaaaa
aaaaaaaaaaaa
aaaaaaaaaaaa
2
aaaaaaaaaaaa
aaaaaaaaaaaa
aaaaaa

View File

@@ -1,170 +0,0 @@
#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;
}

View File

@@ -1,52 +0,0 @@
# 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

View File

@@ -1,18 +0,0 @@
#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;
}

View File

@@ -1,19 +0,0 @@
#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;
}

View File

@@ -1,62 +0,0 @@
#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;
}

View File

@@ -1,44 +0,0 @@
#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;
}

View File

@@ -1,27 +0,0 @@
# Makefile
CC = gcc
CFLAGS = -Wall -Wextra -std=c99
LDFLAGS = -ldl
# Цель по умолчанию
all: task12 libtextlib.so
# Основная программа
task12: task12.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
# Динамическая библиотека
libtextlib.so: textlib.c
$(CC) $(CFLAGS) -fPIC -shared -o $@ $<
# Очистка
clean:
rm -f task12 libtextlib.so input.txt output.txt
# Тест
test: all
echo -e "Hello world\ntest line\nanother" > input.txt
./task12 input.txt output.txt 5 ./libtextlib.so
cat output.txt
.PHONY: all clean test

View File

@@ -1,96 +0,0 @@
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.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 != 5) {
const char *usage =
"Usage: lab2_var12 <input.txt> <output.txt> <max_replacements> <library.so>\n"
"Variant 12: Load text processing library dynamically and process file.\n"
"Library should provide 'process_text' function.\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]);
const char *lib_path = argv[4];
if (cap < 0) {
die_perror("invalid max_replacements", argv[3], -1);
}
// Динамически загружаем библиотеку
void *lib_handle = dlopen(lib_path, RTLD_LAZY);
if (!lib_handle) {
const char *error_msg = dlerror();
char msg[512];
snprintf(msg, sizeof(msg), "dlopen failed: %s\n", error_msg ? error_msg : "unknown error");
(void) write(STDERR_FILENO, msg, strlen(msg));
return -1;
}
// Получаем указатель на функцию обработки текста
long long (*process_text)(const char*, const char*, long long) =
(long long (*)(const char*, const char*, long long)) dlsym(lib_handle, "process_text");
if (!process_text) {
const char *error_msg = dlerror();
char msg[512];
snprintf(msg, sizeof(msg), "dlsym failed: %s\n", error_msg ? error_msg : "unknown error");
(void) write(STDERR_FILENO, msg, strlen(msg));
dlclose(lib_handle);
return -1;
}
// Вызываем функцию из библиотеки
long long result = process_text(in_path, out_path, cap);
if (result < 0) {
die_perror("process_text failed", NULL, -1);
}
// Закрываем библиотеку
dlclose(lib_handle);
// Выводим результат
char res[64];
int m = snprintf(res, sizeof(res), "%lld\n", result);
if (m > 0) {
(void) write(STDOUT_FILENO, res, (size_t) m);
}
return 0;
}

View File

@@ -1,93 +0,0 @@
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#define RBUFSZ 4096
#define WBUFSZ 4096
// Функция обработки текста
long long process_text(const char *in_path, const char *out_path, long long cap) {
int in_fd = open(in_path, O_RDONLY);
if (in_fd < 0) {
return -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) {
close(in_fd);
return -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;
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;
}
} else {
replacing_enabled = 0;
}
}
if (wlen == sizeof(wbuf)) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
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) {
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
break;
} else {
close(in_fd);
close(out_fd);
return -1;
}
}
close(in_fd);
close(out_fd);
return total_replacements;
}

View File

@@ -1,52 +0,0 @@
# 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\n!!@@2211122\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\n!!@@2211122\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

View File

@@ -1,35 +0,0 @@
#include <stddef.h>
int replace_char(char *buf, int key, int *replacements_left) {
(void)key;
int replaced = 0;
size_t i = 0;
while (buf[i] != '\0') {
if (buf[i] == '\n') {
i++;
continue;
}
// Detect start of a symbol run
char symbol = buf[i];
size_t run_start = i;
size_t run_len = 1;
// Count length of run
while (buf[i + run_len] == symbol && buf[i + run_len] != '\n' && buf[i + run_len] != '\0') {
run_len++;
}
// For pairs and longer runs: replace every 2nd, 4th, ...
for (size_t j = 1; j < run_len && *replacements_left > 0; j += 2) {
buf[run_start + j] = ' ';
replaced++;
(*replacements_left)--;
if (*replacements_left == 0) break;
}
i += run_len;
}
return replaced;
}

View File

@@ -1,35 +0,0 @@
#include <stddef.h>
int replace_char(char *buf, int key, int *replacements_left) {
(void)key;
int replaced = 0;
size_t i = 0;
while (buf[i] != '\0') {
if (buf[i] == '\n') {
i++;
continue;
}
// Detect start of a symbol run
char symbol = buf[i];
size_t run_start = i;
size_t run_len = 1;
// Count length of run
while (buf[i + run_len] == symbol && buf[i + run_len] != '\n' && buf[i + run_len] != '\0') {
run_len++;
}
// For pairs and longer runs: replace every 2nd, 4th, ...
for (size_t j = 1; j < run_len && *replacements_left > 0; j += 2) {
buf[run_start + j] = ' ';
replaced++;
(*replacements_left)--;
if (*replacements_left == 0) break;
}
i += run_len;
}
return replaced;
}

View File

@@ -1,62 +0,0 @@
#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");
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;
}

View File

@@ -1,44 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 4096
int replace_char(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, key, &cap);
total += repl_line;
}
fputs(line, fout);
}
fclose(fin);
fclose(fout);
printf("total_replacements: %d\n", total);
return 0;
}

View File

@@ -1,55 +0,0 @@
# Компилятор и флаги
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 не найден"

View File

@@ -1,117 +0,0 @@
#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;
}

View File

@@ -1,129 +0,0 @@
#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;
}

View File

@@ -1,51 +0,0 @@
# Компилятор и флаги
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 не найден"

View File

@@ -1,88 +0,0 @@
#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;
}

View File

@@ -1,170 +0,0 @@
#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;
}

View File

@@ -1,99 +0,0 @@
# 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

View File

@@ -1,144 +0,0 @@
// 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;
}

View File

@@ -1,183 +0,0 @@
// 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;
}

View File

@@ -1,99 +0,0 @@
# 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

View File

@@ -1,144 +0,0 @@
// 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;
}

View File

@@ -1,187 +0,0 @@
// 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;
size_t out_pos = 0;
size_t i = 0;
while (i < input_len && out_pos < output_size - 1) {
unsigned char c = (unsigned char)input[i];
/* Try to form a non-overlapping pair with the next character.
Do not treat newline as part of a pair (preserve line structure). */
if (i + 1 < input_len) {
unsigned char next = (unsigned char)input[i + 1];
if (c != '\n' && next != '\n' && c == next && total_replacements < max_replacements) {
/* write first char of pair */
output[out_pos++] = (char)c;
if (out_pos >= output_size - 1) break;
/* write space instead of second char */
output[out_pos++] = ' ';
total_replacements++;
i += 2; /* skip both chars (non-overlapping) */
continue;
}
}
/* No valid pair -> write current char */
output[out_pos++] = (char)c;
i++;
}
/* If we stopped early but still have room, copy remaining bytes (without forming pairs)
until output buffer full or input ends. This preserves trailing data. */
while (i < input_len && out_pos < output_size - 1) {
output[out_pos++] = input[i++];
}
output[out_pos] = '\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;
}