remove some shi

This commit is contained in:
2025-12-11 08:50:31 +07:00
parent 139f41ae44
commit 6cd4088087
29 changed files with 0 additions and 2456 deletions

View File

@@ -1,107 +0,0 @@
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <cerrno>
#include <cstdlib>
#include <climits>
static bool file_exists(const std::string &path) {
struct stat st{};
return ::stat(path.c_str(), &st) == 0; // stat success => exists [web:59]
}
static std::string make_out_name(const std::string &in) {
std::size_t pos = in.find_last_of('.');
if (pos == std::string::npos) return in + ".out";
return in.substr(0, pos) + ".out";
}
static void print_usage(const char* prog) {
std::cerr << "Usage: " << prog << " <input_file> <replace_count>\n"; // positional args [web:59]
}
static bool parse_ll(const char* s, long long& out) {
if (!s || !*s) return false;
errno = 0;
char* end = nullptr;
long long v = std::strtoll(s, &end, 10); // use endptr and errno [web:59]
if (errno == ERANGE) return false;
if (end == s || *end != '\0') return false;
out = v;
return true;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
print_usage(argv[0]);
return -1;
}
std::string in_path = argv[1];
long long replace_limit = 0;
if (!parse_ll(argv[2], replace_limit) || replace_limit < 0) {
std::cerr << "Error: replace_count must be a non-negative integer.\n";
return -1;
}
if (!file_exists(in_path)) {
std::cerr << "Error: input file does not exist.\n";
return -1;
}
std::ifstream in(in_path);
if (!in) {
std::cerr << "Error: cannot open input file.\n";
return -1;
}
std::string out_path = make_out_name(in_path);
std::ofstream out(out_path);
if (!out) {
std::cerr << "Error: cannot create output file.\n";
return -1;
}
long long performed = 0;
std::string line;
while (performed < replace_limit && std::getline(in, line)) { // stop early when limit hit [web:59]
if (!line.empty()) {
char first = line.front();
for (char &c: line) {
if (c == first && c != ' ') {
c = ' ';
++performed;
if (performed >= replace_limit) break; // cap reached [web:44]
}
}
}
out << line;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
// If limit reached mid-file, copy the rest unchanged
if (performed >= replace_limit) { // stream may be mid-line or between lines [web:59]
// Write remaining lines as-is
if (!in.eof()) {
// Flush any remaining part of current line already written; then dump rest
std::string rest;
while (std::getline(in, rest)) {
out << rest;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
}
}
std::cout << performed << std::endl; // print actual replacements up to limit [web:59]
return 0; // success [web:59]
}

View File

@@ -1 +0,0 @@
g++ -std=c++17 -O2 -Wall -Wextra 12_first_symbols_to_spaces.cpp -o 12_first_symbols_to_spaces

View File

@@ -1,21 +0,0 @@
Здравствуйте, Андрей Васильевич!
TLDR:
ssh pajjilykk@cs.webmaple.ru
cd /home/pajjilykk/CS_LABS/lab_1
cat README.txt
Сообщаю, что лабораторная работа №1 по программированию выполнена и размещена на сервере. Данные для доступа и проверки:
Адрес сервера: cs.webmaple.ru
Логин: pajjilykk
Пароль: NSTU.CS
Путь к коду: /home/pajjilykk/CS_LABS/lab_1
Готов ответить на вопросы по коду и/или защите.
С уважением,
Куриленко Платон, группа АВТ-418

View File

@@ -1,8 +0,0 @@
abcabcABC
Aaaaaa
1112233111
,,,,.,,
leading spaces here
tab leading here
first-letter f repeats: f fff f-f_f
ZzzZzZ

View File

@@ -1 +0,0 @@
./12_first_symbols_to_spaces file.in 3

View File

@@ -1,53 +0,0 @@
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#define BUF_SIZE 1024
// пример программы обработки текстового файла средствами системых вызовов Linux
// учебник "Системное программирование в среде Linux", Гунько А.В., стр. 22
int main (int argc, char * argv [ ])
{
int inputFd, outputFd, openFlags;
mode_t filePerms ;
ssize_t numRead;
char buf[BUF_SIZE];
if (argc != 3)
{
printf("Usage: %s old-file new-file \n", argv[0]); exit(-1);
}
/* Открытие файлов ввода и вывода */
inputFd = open (argv[1], O_RDONLY);
if (inputFd == -1)
{
printf ("Error opening file %s\n", argv[1]) ; exit(-2);
}
openFlags = O_CREAT | O_WRONLY | O_TRUNC;
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* rw - rw - rw - */
outputFd = open (argv [2], openFlags, filePerms);
if (outputFd == -1)
{
printf ("Error opening file %s\n ", argv[2]) ; exit(-3);
}
/* Перемещение данных до достижения конца файла ввода или возникновения ошибки */
while ((numRead = read (inputFd, buf, BUF_SIZE)) > 0)
{
if (write (outputFd, buf, numRead) != numRead)
{
printf ("couldn't write whole buffer\n "); exit(-4);
}
if (numRead == -1)
{
printf ("read error\n "); exit(-5);
}
if (close (inputFd ) == -1 )
{
printf ("close input error\n"); exit(-6);
}
if (close (outputFd ) == -1 )
{
printf ("close output error\n"); exit(-7);
}
}
exit(EXIT_SUCCESS);
}

View File

@@ -1,32 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
// пример программы обработки текстового файла средствами системых вызовов Linux
// учебник "Системное программирование в среде Linux", Гунько А.В.
int main(int argc, char *argv[]) {
int handle, numRead, total= 0;
char buf;
if (argc<2) {
printf("Usage: file textfile\n");
exit(-1);
}
// низкоуровневое открытие файла на чтение
handle = open( argv[1], O_RDONLY);
if (handle<0) {
printf("Error %d (%s) while open file: %s!\n",errno, strerror(errno),argv[1]);
exit(-2);
}
// цикл до конца файла
do {
// посимвольное чтение из файла
numRead = read( handle, &buf, 1);
if (buf == 0x20) total++; }
while (numRead > 0);
// Закрытие файла
close( handle);
printf("(PID: %d), File %s, spaces = %d\n", getpid(), argv[1], total);
// возвращаемое программой значение
return( total); }

View File

@@ -1,5 +0,0 @@
Hi! This is a test.
Wait: are commas, periods, and exclamations replaced?
Let's check!
@#$%&*)_+

View File

@@ -1,6 +0,0 @@
Hi9 This is a test9
Wait9 are commas9 periods9 and exclamations replaced9
Let's check9
@#$%&*)_+

Binary file not shown.

View File

@@ -1,76 +0,0 @@
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
using namespace std;
// ???????? ????????????? ?????
bool fileExists(const string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
// ????????? ????? ????????? ????? ? ??????? ?????????? ?? ".out"
string getOutputFileName(const string& inputFileName) {
size_t pos = inputFileName.find_last_of('.');
if (pos == string::npos) {
// ???? ?????????? ???, ????????? .out
return inputFileName + ".out";
}
return inputFileName.substr(0, pos) + ".out"; // ???????? ??????????
}
// ????????, ???????? ?? ?????? ?????? ??????????, ?????????? ??????
bool isSign(char c) {
return (c == '!' || c == '?' || c == '.' || c == ',' || c == ';' || c == ':');
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cerr << "Error: Missing arguments.\nUsage: " << argv[0] << " <inputfile> <symbol>\n";
return -1;
}
string inputFileName = argv[1];
char replacementSymbol = argv[2][0];
if (!fileExists(inputFileName)) {
cerr << "Error: Input file \"" << inputFileName << "\" does not exist.\n";
return -1;
}
string outputFileName = getOutputFileName(inputFileName);
ifstream inFile(inputFileName);
if (!inFile) {
cerr << "Error: Cannot open input file.\n";
return -1;
}
ofstream outFile(outputFileName);
if (!outFile) {
cerr << "Error: Cannot create output file.\n";
return -1;
}
int replaceCount = 0;
char ch;
while (inFile.get(ch)) {
if (isSign(ch)) {
ch = replacementSymbol;
replaceCount++;
}
outFile.put(ch);
if (!outFile) {
cerr << "Error: Write error occurred.\n";
return -1;
}
}
inFile.close();
outFile.close();
cout << replaceCount << endl; // ??????? ????? ?????
return replaceCount;
}

View File

@@ -1,51 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -g
LDFLAGS_IPC = -lrt -pthread
SHM_NAME ?= /myshm
SEM_CLIENT_NAME ?= /sem_client
SEM_SERVER_NAME ?= /sem_server
SERVER_ITERS ?= 1000
all: shm
shm: server client
server: server.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
client: client.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
test_server: shm
@echo "=== Запуск сервера POSIX SHM+SEM ==="
@echo "В другом терминале выполните: make test_client"
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS)
test_client: shm
@echo "=== Запуск клиента, чтение input.txt, вывод на stdout ==="
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME)
test_all: shm
@echo "=== Автотест POSIX SHM+SEM с файлами input.txt/output.txt ==="
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS) & \
SRV=$$!; \
sleep 1; \
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME); \
wait $$SRV
clean:
@echo "Очистка..."
rm -f server client
rm -f output.txt
help:
@echo "Available targets:"
@echo " shm - Build POSIX SHM+SEM programs"
@echo " test_server - Run SHM+SEM server (client in another terminal)"
@echo " test_client - Run client reading input.txt"
@echo " test_all - Automatic end-to-end test with input.txt/output.txt"
@echo " clean - Remove built files"
@echo " help - Show this help"
.PHONY: all shm test_server test_client test_all clean help

View File

@@ -1,141 +0,0 @@
// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <unistd.h>
#define SHM_BUFFER_SIZE 1024
typedef struct {
int has_data;
int result_code;
char buffer[SHM_BUFFER_SIZE];
} shared_block_t;
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr,
"Usage: %s <shm_name> <sem_client_name> <sem_server_name>\n",
argv[0]);
return -1;
}
const char *shm_name = argv[1];
const char *sem_client_name = argv[2];
const char *sem_server_name = argv[3];
int shm_fd = shm_open(shm_name, O_RDWR, 0);
if (shm_fd == -1) {
perror("shm_open");
return -1;
}
shared_block_t *shm_ptr = mmap(NULL,
sizeof(shared_block_t),
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_fd,
0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
return -1;
}
if (close(shm_fd) == -1) {
perror("close");
}
sem_t *sem_client = sem_open(sem_client_name, 0);
if (sem_client == SEM_FAILED) {
perror("sem_open(sem_client)");
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
sem_t *sem_server = sem_open(sem_server_name, 0);
if (sem_server == SEM_FAILED) {
perror("sem_open(sem_server)");
sem_close(sem_client);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
FILE *fin = fopen("input.txt", "r");
if (!fin) {
perror("fopen(input.txt)");
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
char input[SHM_BUFFER_SIZE];
while (fgets(input, sizeof(input), fin) != NULL) {
size_t len = strlen(input);
if (len > 0 && input[len - 1] == '\n') {
input[len - 1] = '\0';
}
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
strncpy(shm_ptr->buffer, input, SHM_BUFFER_SIZE - 1);
shm_ptr->buffer[SHM_BUFFER_SIZE - 1] = '\0';
shm_ptr->has_data = 1;
if (sem_post(sem_client) == -1) {
perror("sem_post(sem_client)");
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
if (sem_wait(sem_server) == -1) {
perror("sem_wait(sem_server)");
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
if (shm_ptr->result_code != 0) {
fprintf(stderr,
"Server reported error, result_code = %d\n",
shm_ptr->result_code);
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
printf("%s\n", shm_ptr->buffer);
}
if (fclose(fin) == EOF) {
perror("fclose(input.txt)");
}
if (sem_close(sem_client) == -1) {
perror("sem_close(sem_client)");
}
if (sem_close(sem_server) == -1) {
perror("sem_close(sem_server)");
}
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
perror("munmap");
}
return 0;
}

View File

@@ -1,6 +0,0 @@
abacaba
xxxxxx
hello
aaaaa
1abc1d1e1
qwerty

View File

@@ -1,185 +0,0 @@
// server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <unistd.h>
#define SHM_BUFFER_SIZE 1024
typedef struct {
int has_data;
int result_code;
char buffer[SHM_BUFFER_SIZE];
} shared_block_t;
static void process_line(char *s) {
if (!s) return;
for (size_t i = 0; s[i] != '\0'; ++i) {
if ((i + 1) % 3 == 0) {
s[i] = ' ';
}
}
}
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr,
"Usage: %s <shm_name> <sem_client_name> <sem_server_name> [iterations]\n",
argv[0]);
return -1;
}
const char *shm_name = argv[1];
const char *sem_client_name = argv[2];
const char *sem_server_name = argv[3];
int iterations = -1;
if (argc >= 5) {
char *endptr = NULL;
unsigned long tmp = strtoul(argv[4], &endptr, 10);
if (endptr == argv[4] || *endptr != '\0') {
fprintf(stderr, "Invalid iterations value: '%s'\n", argv[4]);
return -1;
}
iterations = (int) tmp;
}
shm_unlink(shm_name);
sem_unlink(sem_client_name);
sem_unlink(sem_server_name);
int shm_fd = shm_open(shm_name,
O_CREAT | O_EXCL | O_RDWR,
S_IRUSR | S_IWUSR);
if (shm_fd == -1) {
perror("shm_open");
return -1;
}
if (ftruncate(shm_fd, sizeof(shared_block_t)) == -1) {
perror("ftruncate");
close(shm_fd);
shm_unlink(shm_name);
return -1;
}
shared_block_t *shm_ptr = mmap(NULL,
sizeof(shared_block_t),
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_fd,
0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
shm_unlink(shm_name);
return -1;
}
if (close(shm_fd) == -1) {
perror("close");
}
shm_ptr->has_data = 0;
shm_ptr->result_code = 0;
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
sem_t *sem_client = sem_open(sem_client_name,
O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR,
0);
if (sem_client == SEM_FAILED) {
perror("sem_open(sem_client)");
munmap(shm_ptr, sizeof(shared_block_t));
shm_unlink(shm_name);
return -1;
}
sem_t *sem_server = sem_open(sem_server_name,
O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR,
0);
if (sem_server == SEM_FAILED) {
perror("sem_open(sem_server)");
sem_close(sem_client);
sem_unlink(sem_client_name);
munmap(shm_ptr, sizeof(shared_block_t));
shm_unlink(shm_name);
return -1;
}
FILE *fout = fopen("output.txt", "w");
if (!fout) {
perror("fopen(output.txt)");
}
int processed_count = 0;
while (iterations < 0 || processed_count < iterations) {
if (sem_wait(sem_client) == -1) {
perror("sem_wait(sem_client)");
processed_count = -1;
break;
}
if (!shm_ptr->has_data) {
fprintf(stderr, "Warning: sem_client posted, but has_data == 0\n");
shm_ptr->result_code = -1;
} else {
process_line(shm_ptr->buffer);
shm_ptr->result_code = 0;
shm_ptr->has_data = 0;
processed_count++;
if (fout) {
fprintf(fout, "%s\n", shm_ptr->buffer);
fflush(fout);
}
}
if (sem_post(sem_server) == -1) {
perror("sem_post(sem_server)");
processed_count = -1;
break;
}
}
if (fout && fclose(fout) == EOF) {
perror("fclose(output.txt)");
}
if (processed_count >= 0) {
printf("%d\n", processed_count);
} else {
printf("-1\n");
}
if (sem_close(sem_client) == -1) {
perror("sem_close(sem_client)");
}
if (sem_close(sem_server) == -1) {
perror("sem_close(sem_server)");
}
if (sem_unlink(sem_client_name) == -1) {
perror("sem_unlink(sem_client)");
}
if (sem_unlink(sem_server_name) == -1) {
perror("sem_unlink(sem_server)");
}
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
perror("munmap");
}
if (shm_unlink(shm_name) == -1) {
perror("shm_unlink");
}
return 0;
}

View File

@@ -1,51 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -g
LDFLAGS_IPC = -lrt -pthread
SHM_NAME ?= /myshm
SEM_CLIENT_NAME ?= /sem_client
SEM_SERVER_NAME ?= /sem_server
SERVER_ITERS ?= 1000
all: shm
shm: server client
server: server.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
client: client.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS_IPC)
test_server: shm
@echo "=== Запуск сервера POSIX SHM+SEM ==="
@echo "В другом терминале выполните: make test_client"
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS)
test_client: shm
@echo "=== Запуск клиента, чтение input.txt, вывод на stdout ==="
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME)
test_all: shm
@echo "=== Автотест POSIX SHM+SEM с файлами input.txt/output.txt ==="
./server $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME) $(SERVER_ITERS) & \
SRV=$$!; \
sleep 1; \
./client $(SHM_NAME) $(SEM_CLIENT_NAME) $(SEM_SERVER_NAME); \
wait $$SRV
clean:
@echo "Очистка..."
rm -f server client
rm -f output.txt
help:
@echo "Available targets:"
@echo " shm - Build POSIX SHM+SEM programs"
@echo " test_server - Run SHM+SEM server (client in another terminal)"
@echo " test_client - Run client reading input.txt"
@echo " test_all - Automatic end-to-end test with input.txt/output.txt"
@echo " clean - Remove built files"
@echo " help - Show this help"
.PHONY: all shm test_server test_client test_all clean help

View File

@@ -1,147 +0,0 @@
// client.c
// Клиент: читает строки из input.txt, передаёт их серверу через shared memory,
// ожидает обработку и печатает результат на stdout. [file:21][file:22]
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fgets
#include <stdlib.h> // exit, EXIT_FAILURE
#include <string.h> // memset, strncpy, strlen
#include <errno.h> // errno
#include <fcntl.h> // O_RDWR
#include <sys/mman.h> // shm_open, mmap, munmap
#include <sys/stat.h> // mode_t
#include <semaphore.h> // sem_t, sem_open, sem_close, sem_wait, sem_post
#include <unistd.h> // close
#define SHM_BUFFER_SIZE 1024 // Должен совпадать с server.c. [file:21]
typedef struct {
int has_data; // Флаг наличия данных. [file:21]
int result_code; // Код результата обработки. [file:21]
char buffer[SHM_BUFFER_SIZE]; // Буфер строки. [file:21]
} shared_block_t;
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr,
"Usage: %s <shm_name> <sem_client_name> <sem_server_name>\n",
argv[0]);
return -1;
}
const char *shm_name = argv[1];
const char *sem_client_name = argv[2];
const char *sem_server_name = argv[3];
// Открываем существующий shm. [file:21]
int shm_fd = shm_open(shm_name, O_RDWR, 0);
if (shm_fd == -1) {
perror("shm_open");
return -1;
}
shared_block_t *shm_ptr = mmap(NULL,
sizeof(shared_block_t),
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_fd,
0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
return -1;
}
if (close(shm_fd) == -1) {
perror("close");
}
// Открываем семафоры. [file:21]
sem_t *sem_client = sem_open(sem_client_name, 0);
if (sem_client == SEM_FAILED) {
perror("sem_open(sem_client)");
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
sem_t *sem_server = sem_open(sem_server_name, 0);
if (sem_server == SEM_FAILED) {
perror("sem_open(sem_server)");
sem_close(sem_client);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
// Открываем input.txt. [file:22]
FILE *fin = fopen("input.txt", "r");
if (!fin) {
perror("fopen(input.txt)");
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
char input[SHM_BUFFER_SIZE];
while (fgets(input, sizeof(input), fin) != NULL) {
size_t len = strlen(input);
if (len > 0 && input[len - 1] == '\n') {
input[len - 1] = '\0';
}
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
strncpy(shm_ptr->buffer, input, SHM_BUFFER_SIZE - 1);
shm_ptr->buffer[SHM_BUFFER_SIZE - 1] = '\0';
shm_ptr->has_data = 1;
if (sem_post(sem_client) == -1) {
perror("sem_post(sem_client)");
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
if (sem_wait(sem_server) == -1) {
perror("sem_wait(sem_server)");
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
if (shm_ptr->result_code != 0) {
fprintf(stderr,
"Server reported error, result_code = %d\n",
shm_ptr->result_code);
fclose(fin);
sem_close(sem_client);
sem_close(sem_server);
munmap(shm_ptr, sizeof(shared_block_t));
return -1;
}
printf("%s\n", shm_ptr->buffer);
}
if (fclose(fin) == EOF) {
perror("fclose(input.txt)");
}
if (sem_close(sem_client) == -1) {
perror("sem_close(sem_client)");
}
if (sem_close(sem_server) == -1) {
perror("sem_close(sem_server)");
}
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
perror("munmap");
}
return 0;
}

View File

@@ -1,6 +0,0 @@
abacaba
xxxxxx
hello
aaaaa
1abc1d1e1
qwerty

View File

@@ -1,210 +0,0 @@
// server.c
// Сервер POSIX IPC: разделяемая память + именованные семафоры. [file:21]
// Задача: во всех парах одинаковых соседних символов второй символ заменить на пробел. [file:22]
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fprintf
#include <stdlib.h> // exit, EXIT_FAILURE, strtoul
#include <string.h> // memset, strncpy, strlen
#include <errno.h> // errno
#include <fcntl.h> // O_CREAT, O_EXCL, O_RDWR
#include <sys/mman.h> // shm_open, mmap, munmap
#include <sys/stat.h> // S_IRUSR, S_IWUSR
#include <semaphore.h> // sem_t, sem_open, sem_close, sem_unlink, sem_wait, sem_post
#include <unistd.h> // ftruncate, close
#define SHM_BUFFER_SIZE 1024 // Максимальный размер строки в shared memory. [file:21]
// Структура разделяемой памяти. [file:21]
typedef struct {
int has_data; // 1, если клиент записал строку. [file:21]
int result_code; // 0 - успех, -1 - ошибка. [file:21]
char buffer[SHM_BUFFER_SIZE]; // Буфер для строки. [file:21]
} shared_block_t;
// Обработка строки по новому заданию: [file:22]
// "Во всех парах одинаковых символов второй символ заменить на пробел".
static void process_line(char *s) {
if (!s) {
return;
}
for (size_t i = 0; s[i] != '\0'; ++i) {
// Идём по всей строке. [file:22]
if (s[i] != '\0' && s[i + 1] != '\0' && s[i] == s[i + 1]) {
// Если два соседних символа равны, второй заменяем на пробел. [file:22]
s[i + 1] = ' ';
// Можно сдвинуться дальше, чтобы не склеивать новые пары искусственно. [file:22]
// Но по условию достаточно просто заменить второй символ.
}
}
}
int main(int argc, char *argv[]) {
// argv[1] - имя shm, argv[2] - имя sem_client, argv[3] - имя sem_server, argv[4] - итерации. [file:22]
if (argc < 4) {
fprintf(stderr,
"Usage: %s <shm_name> <sem_client_name> <sem_server_name> [iterations]\n",
argv[0]);
return -1;
}
const char *shm_name = argv[1];
const char *sem_client_name = argv[2];
const char *sem_server_name = argv[3];
int iterations = -1; // -1 = работать до сигнала/внешнего завершения. [file:22]
if (argc >= 5) {
char *endptr = NULL;
unsigned long tmp = strtoul(argv[4], &endptr, 10);
if (endptr == argv[4] || *endptr != '\0') {
fprintf(stderr, "Invalid iterations value: '%s'\n", argv[4]);
return -1;
}
iterations = (int) tmp;
}
// Простая зачистка возможных старых IPC-объектов. [file:21]
shm_unlink(shm_name);
sem_unlink(sem_client_name);
sem_unlink(sem_server_name);
// Создаём shared memory. [file:21]
int shm_fd = shm_open(shm_name,
O_CREAT | O_EXCL | O_RDWR,
S_IRUSR | S_IWUSR);
if (shm_fd == -1) {
perror("shm_open");
return -1;
}
if (ftruncate(shm_fd, sizeof(shared_block_t)) == -1) {
perror("ftruncate");
close(shm_fd);
shm_unlink(shm_name);
return -1;
}
shared_block_t *shm_ptr = mmap(NULL,
sizeof(shared_block_t),
PROT_READ | PROT_WRITE,
MAP_SHARED,
shm_fd,
0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
close(shm_fd);
shm_unlink(shm_name);
return -1;
}
if (close(shm_fd) == -1) {
perror("close");
}
// Инициализация shared memory. [file:21]
shm_ptr->has_data = 0;
shm_ptr->result_code = 0;
memset(shm_ptr->buffer, 0, sizeof(shm_ptr->buffer));
// Создаём семафоры. [file:21]
sem_t *sem_client = sem_open(sem_client_name,
O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR,
0);
if (sem_client == SEM_FAILED) {
perror("sem_open(sem_client)");
munmap(shm_ptr, sizeof(shared_block_t));
shm_unlink(shm_name);
return -1;
}
sem_t *sem_server = sem_open(sem_server_name,
O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR,
0);
if (sem_server == SEM_FAILED) {
perror("sem_open(sem_server)");
sem_close(sem_client);
sem_unlink(sem_client_name);
munmap(shm_ptr, sizeof(shared_block_t));
shm_unlink(shm_name);
return -1;
}
// Открываем файл вывода. [file:22]
FILE *fout = fopen("output.txt", "w");
if (!fout) {
perror("fopen(output.txt)");
// Продолжаем работать только через shared memory. [file:21]
}
int processed_count = 0; // Сколько строк обработано. [file:22]
while (iterations < 0 || processed_count < iterations) {
// Ждём строку от клиента. [file:21]
if (sem_wait(sem_client) == -1) {
perror("sem_wait(sem_client)");
processed_count = -1;
break;
}
if (!shm_ptr->has_data) {
fprintf(stderr, "Warning: sem_client posted, but has_data == 0\n");
shm_ptr->result_code = -1;
} else {
// Обрабатываем строку по новому заданию. [file:22]
process_line(shm_ptr->buffer);
shm_ptr->result_code = 0;
shm_ptr->has_data = 0;
processed_count++;
if (fout) {
fprintf(fout, "%s\n", shm_ptr->buffer);
fflush(fout);
}
}
// Сообщаем клиенту, что результат готов. [file:21]
if (sem_post(sem_server) == -1) {
perror("sem_post(sem_server)");
processed_count = -1;
break;
}
}
if (fout && fclose(fout) == EOF) {
perror("fclose(output.txt)");
}
// Выводим число операций или -1. [file:22]
if (processed_count >= 0) {
printf("%d\n", processed_count);
} else {
printf("-1\n");
}
// Очистка IPC-объектов. [file:21]
if (sem_close(sem_client) == -1) {
perror("sem_close(sem_client)");
}
if (sem_close(sem_server) == -1) {
perror("sem_close(sem_server)");
}
if (sem_unlink(sem_client_name) == -1) {
perror("sem_unlink(sem_client)");
}
if (sem_unlink(sem_server_name) == -1) {
perror("sem_unlink(sem_server)");
}
if (munmap(shm_ptr, sizeof(shared_block_t)) == -1) {
perror("munmap");
}
if (shm_unlink(shm_name) == -1) {
perror("shm_unlink");
}
return 0;
}

View File

@@ -1,43 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c11 -g -pthread
MAX_REPL ?= 100
INPUT1 ?= in1.txt
OUTPUT1 ?= out1.txt
INPUT2 ?= in2.txt
OUTPUT2 ?= out2.txt
all: threads_third
threads_third: main.c
$(CC) $(CFLAGS) -o $@ $<
test_two: threads_third
@echo "=== Тест с двумя файлами ==="
@printf "abcdefghijk\n" > $(INPUT1)
@printf "xxxxxxxxxx\n" > $(INPUT2)
./threads_third $(MAX_REPL) $(INPUT1) $(OUTPUT1) $(INPUT2) $(OUTPUT2)
@echo "--- $(INPUT1) -> $(OUTPUT1) ---"
@cat $(INPUT1)
@echo "-----"
@cat $(OUTPUT1)
@echo
@echo "--- $(INPUT2) -> $(OUTPUT2) ---"
@cat $(INPUT2)
@echo "-----"
@cat $(OUTPUT2)
clean:
@echo "Очистка..."
rm -f threads_third
rm -f in1.txt out1.txt in2.txt out2.txt
help:
@echo "Available targets:"
@echo " all - build threads_third"
@echo " test_two - run two-file multithread test"
@echo " clean - remove binaries and test files"
@echo " help - show this help"
.PHONY: all test_one test_two test_all clean help

View File

@@ -1,276 +0,0 @@
// threads_third.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#define RBUFSZ 4096
#define WBUFSZ 4096
#define MAX_THREADS 100
typedef struct {
const char *input_path;
const char *output_path;
long long max_repl;
int thread_index;
int result;
} ThreadTask;
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
static void die_perror_thread(const char *what,
const char *path,
int exit_code) {
int saved = errno;
char msg[512];
if (path) {
snprintf(msg, sizeof(msg),
"%s: %s: %s\n", what, path, strerror(saved));
} else {
snprintf(msg, sizeof(msg),
"%s: %s\n", what, strerror(saved));
}
pthread_mutex_lock(&log_mutex);
write(STDERR_FILENO, msg, strlen(msg));
pthread_mutex_unlock(&log_mutex);
(void) exit_code;
}
static long long parse_ll(const char *s) {
char *end = NULL;
errno = 0;
long long v = strtoll(s, &end, 10);
if (errno != 0 || end == s || *end != '\0' || v < 0) {
errno = EINVAL;
return -1;
}
return v;
}
static int process_file_third(const char *in_path,
const char *out_path,
long long cap) {
int in_fd = open(in_path, O_RDONLY);
if (in_fd < 0) {
die_perror_thread("open input failed", in_path, -1);
return -1;
}
mode_t perms = S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH;
int out_fd = open(out_path,
O_CREAT | O_WRONLY | O_TRUNC,
perms);
if (out_fd < 0) {
die_perror_thread("open output failed", out_path, -1);
close(in_fd);
return -1;
}
char rbuf[RBUFSZ];
char wbuf[WBUFSZ];
size_t wlen = 0;
long long total_replacements = 0;
long long pos_in_file = 0;
for (;;) {
ssize_t n = read(in_fd, rbuf, sizeof(rbuf));
if (n > 0) {
for (ssize_t i = 0; i < n; i++, pos_in_file++) {
unsigned char c = (unsigned char) rbuf[i];
unsigned char outc = c;
if ((pos_in_file + 1) % 3 == 0 && total_replacements < cap) {
outc = ' ';
total_replacements++;
}
if (wlen == sizeof(wbuf)) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
die_perror_thread("write failed", out_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
wbuf[wlen++] = (char) outc;
}
} else if (n == 0) {
if (wlen > 0) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
die_perror_thread("write failed", out_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
break;
} else {
die_perror_thread("read failed", in_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
}
if (close(in_fd) < 0) {
die_perror_thread("close input failed", in_path, -1);
close(out_fd);
return -1;
}
if (close(out_fd) < 0) {
die_perror_thread("close output failed", out_path, -1);
return -1;
}
pthread_mutex_lock(&log_mutex);
char res[64];
int m = snprintf(res, sizeof(res), "%lld\n", total_replacements);
if (m > 0) {
write(STDOUT_FILENO, res, (size_t) m);
}
pthread_mutex_unlock(&log_mutex);
return 0;
}
static void *thread_func(void *arg) {
ThreadTask *task = (ThreadTask *) arg;
pthread_mutex_lock(&log_mutex);
printf("[thread %d] start: %s -> %s, max_repl=%lld\n",
task->thread_index,
task->input_path,
task->output_path,
task->max_repl);
pthread_mutex_unlock(&log_mutex);
int rc = process_file_third(task->input_path,
task->output_path,
task->max_repl);
task->result = rc;
pthread_mutex_lock(&log_mutex);
printf("[thread %d] finished with code %d\n",
task->thread_index,
task->result);
pthread_mutex_unlock(&log_mutex);
return NULL;
}
static void print_usage(const char *progname) {
fprintf(stderr,
"Usage: %s <max_replacements> <input1> <output1> [<input2> <output2> ...]\n",
progname);
fprintf(stderr,
"Example: %s 100 in1.txt out1.txt in2.txt out2.txt\n",
progname);
}
int main(int argc, char *argv[]) {
if (argc < 4 || ((argc - 2) % 2) != 0) {
fprintf(stderr,
"ERROR: Недостаточное или неверное количество аргументов\n");
print_usage(argv[0]);
return -1;
}
long long cap = parse_ll(argv[1]);
if (cap < 0) {
die_perror_thread("invalid max_replacements", argv[1], -1);
return -1;
}
int num_files = (argc - 2) / 2;
if (num_files > MAX_THREADS) {
fprintf(stderr,
"ERROR: Слишком много файлов (максимум %d пар)\n",
MAX_THREADS);
return -1;
}
printf("=== Многопоточная обработка: каждый третий символ -> пробел ===\n");
printf("Главный поток TID: %lu\n", (unsigned long) pthread_self());
printf("Максимум замен на файл: %lld\n", cap);
printf("Количество файловых пар: %d\n\n", num_files);
pthread_t threads[MAX_THREADS];
ThreadTask tasks[MAX_THREADS];
for (int i = 0; i < num_files; i++) {
const char *input_path = argv[2 + i * 2];
const char *output_path = argv[3 + i * 2];
tasks[i].input_path = input_path;
tasks[i].output_path = output_path;
tasks[i].max_repl = cap;
tasks[i].thread_index = i + 1;
tasks[i].result = -1;
int rc = pthread_create(&threads[i],
NULL,
thread_func,
&tasks[i]);
if (rc != 0) {
errno = rc;
die_perror_thread("pthread_create failed", NULL, -1);
tasks[i].result = -1;
}
}
int success_count = 0;
int error_count = 0;
for (int i = 0; i < num_files; i++) {
if (!threads[i]) {
error_count++;
continue;
}
int rc = pthread_join(threads[i], NULL);
if (rc != 0) {
errno = rc;
die_perror_thread("pthread_join failed", NULL, -1);
error_count++;
continue;
}
if (tasks[i].result == 0) {
success_count++;
} else {
error_count++;
}
}
printf("\n=== Итоговая статистика ===\n");
printf("Всего потоков: %d\n", num_files);
printf("Успешно завершено: %d\n", success_count);
printf("С ошибкой: %d\n", error_count);
if (error_count > 0) {
printf("\nОБЩИЙ СТАТУС: Завершено с ошибками\n");
return -1;
} else {
printf("\nОБЩИЙ СТАТУС: Все потоки завершены успешно\n");
return 0;
}
}

View File

@@ -1,42 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c11 -g -pthread
MAX_REPL ?= 100
INPUT1 ?= in1.txt
OUTPUT1 ?= out1.txt
INPUT2 ?= in2.txt
OUTPUT2 ?= out2.txt
all: threads_pairs
threads_pairs: main.c
$(CC) $(CFLAGS) -o $@ $<
test_all: threads_pairs
@echo "=== Тест с двумя файлами ==="
@printf "aabb\nzzzz\n" > $(INPUT1)
@printf "hello\nkkk\n" > $(INPUT2)
./threads_pairs $(MAX_REPL) $(INPUT1) $(OUTPUT1) $(INPUT2) $(OUTPUT2)
@echo "--- $(INPUT1) -> $(OUTPUT1) ---"
@cat $(INPUT1)
@echo "-----"
@cat $(OUTPUT1)
@echo
@echo "--- $(INPUT2) -> $(OUTPUT2) ---"
@cat $(INPUT2)
@echo "-----"
@cat $(OUTPUT2)
clean:
@echo "Очистка..."
rm -f threads_pairs
rm -f in1.txt out1.txt in2.txt out2.txt
help:
@echo "Available targets:"
@echo " all - build threads_pairs"
@echo " test_all - run all tests"
@echo " clean - remove binaries and test files"
@echo " help - show this help"
.PHONY: all test_one test_two test_all clean help

View File

@@ -1,300 +0,0 @@
// threads_pairs.c
// Лабораторная №7: многопоточное программирование. [file:22]
// Задача: во всех парах одинаковых соседних символов второй символ заменить на пробел. [file:22]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#define RBUFSZ 4096
#define WBUFSZ 4096
#define MAX_THREADS 100
typedef struct {
const char *input_path;
const char *output_path;
long long max_repl;
int thread_index;
int result;
} ThreadTask;
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
static void die_perror_thread(const char *what,
const char *path,
int exit_code) {
int saved = errno;
char msg[512];
if (path) {
snprintf(msg, sizeof(msg),
"%s: %s: %s\n", what, path, strerror(saved));
} else {
snprintf(msg, sizeof(msg),
"%s: %s\n", what, strerror(saved));
}
pthread_mutex_lock(&log_mutex);
write(STDERR_FILENO, msg, strlen(msg));
pthread_mutex_unlock(&log_mutex);
(void) exit_code;
}
static long long parse_ll(const char *s) {
char *end = NULL;
errno = 0;
long long v = strtoll(s, &end, 10);
if (errno != 0 || end == s || *end != '\0' || v < 0) {
errno = EINVAL;
return -1;
}
return v;
}
// Обработка файла по задаче: во всех парах одинаковых символов второй заменить на пробел. [file:22]
static int process_file_pairs(const char *in_path,
const char *out_path,
long long cap) {
int in_fd = open(in_path, O_RDONLY);
if (in_fd < 0) {
die_perror_thread("open input failed", in_path, -1);
return -1;
}
mode_t perms = S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH;
int out_fd = open(out_path,
O_CREAT | O_WRONLY | O_TRUNC,
perms);
if (out_fd < 0) {
die_perror_thread("open output failed", out_path, -1);
close(in_fd);
return -1;
}
char rbuf[RBUFSZ];
char wbuf[WBUFSZ];
size_t wlen = 0;
long long total_replacements = 0;
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];
unsigned char outc = c;
if (total_replacements < cap &&
i + 1 < n &&
(unsigned char) rbuf[i] == (unsigned char) rbuf[i + 1]) {
outc = c;
if (total_replacements < cap) {
outc = c; // первый из пары остаётся
if (wlen == sizeof(wbuf)) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
die_perror_thread("write failed", out_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
wbuf[wlen++] = (char) outc;
i++;
unsigned char c2 = (unsigned char) rbuf[i];
outc = c2;
if (total_replacements < cap) {
outc = ' ';
total_replacements++;
}
}
}
if (wlen == sizeof(wbuf)) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
die_perror_thread("write failed", out_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
wbuf[wlen++] = (char) outc;
}
} else if (n == 0) {
if (wlen > 0) {
ssize_t wrote = write(out_fd, wbuf, wlen);
if (wrote < 0 || (size_t) wrote != wlen) {
die_perror_thread("write failed", out_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
wlen = 0;
}
break;
} else {
die_perror_thread("read failed", in_path, -1);
close(in_fd);
close(out_fd);
return -1;
}
}
if (close(in_fd) < 0) {
die_perror_thread("close input failed", in_path, -1);
close(out_fd);
return -1;
}
if (close(out_fd) < 0) {
die_perror_thread("close output failed", out_path, -1);
return -1;
}
pthread_mutex_lock(&log_mutex);
char res[64];
int m = snprintf(res, sizeof(res), "%lld\n", total_replacements);
if (m > 0) {
write(STDOUT_FILENO, res, (size_t) m);
}
pthread_mutex_unlock(&log_mutex);
return 0;
}
static void *thread_func(void *arg) {
ThreadTask *task = (ThreadTask *) arg;
pthread_mutex_lock(&log_mutex);
printf("[thread %d] start: %s -> %s, max_repl=%lld\n",
task->thread_index,
task->input_path,
task->output_path,
task->max_repl);
pthread_mutex_unlock(&log_mutex);
int rc = process_file_pairs(task->input_path,
task->output_path,
task->max_repl);
task->result = rc;
pthread_mutex_lock(&log_mutex);
printf("[thread %d] finished with code %d\n",
task->thread_index,
task->result);
pthread_mutex_unlock(&log_mutex);
return NULL;
}
static void print_usage(const char *progname) {
fprintf(stderr,
"Usage: %s <max_replacements> <input1> <output1> [<input2> <output2> ...]\n",
progname);
fprintf(stderr,
"Example: %s 100 in1.txt out1.txt in2.txt out2.txt\n",
progname);
}
int main(int argc, char *argv[]) {
if (argc < 4 || ((argc - 2) % 2) != 0) {
fprintf(stderr,
"ERROR: Недостаточное или неверное количество аргументов\n");
print_usage(argv[0]);
return -1;
}
long long cap = parse_ll(argv[1]);
if (cap < 0) {
die_perror_thread("invalid max_replacements", argv[1], -1);
return -1;
}
int num_files = (argc - 2) / 2;
if (num_files > MAX_THREADS) {
fprintf(stderr,
"ERROR: Слишком много файлов (максимум %d пар)\n",
MAX_THREADS);
return -1;
}
printf("=== Многопоточная обработка: пары одинаковых символов ===\n");
printf("Главный поток TID: %lu\n", (unsigned long) pthread_self());
printf("Максимум замен на файл: %lld\n", cap);
printf("Количество файловых пар: %d\n\n", num_files);
pthread_t threads[MAX_THREADS];
ThreadTask tasks[MAX_THREADS];
for (int i = 0; i < num_files; i++) {
const char *input_path = argv[2 + i * 2];
const char *output_path = argv[3 + i * 2];
tasks[i].input_path = input_path;
tasks[i].output_path = output_path;
tasks[i].max_repl = cap;
tasks[i].thread_index = i + 1;
tasks[i].result = -1;
int rc = pthread_create(&threads[i],
NULL,
thread_func,
&tasks[i]);
if (rc != 0) {
errno = rc;
die_perror_thread("pthread_create failed", NULL, -1);
tasks[i].result = -1;
}
}
int success_count = 0;
int error_count = 0;
for (int i = 0; i < num_files; i++) {
if (!threads[i]) {
error_count++;
continue;
}
int rc = pthread_join(threads[i], NULL);
if (rc != 0) {
errno = rc;
die_perror_thread("pthread_join failed", NULL, -1);
error_count++;
continue;
}
if (tasks[i].result == 0) {
success_count++;
} else {
error_count++;
}
}
printf("\n=== Итоговая статистика ===\n");
printf("Всего потоков: %d\n", num_files);
printf("Успешно завершено: %d\n", success_count);
printf("С ошибкой: %d\n", error_count);
if (error_count > 0) {
printf("\nОБЩИЙ СТАТУС: Завершено с ошибками\n");
return -1;
} else {
printf("\nОБЩИЙ СТАТУС: Все потоки завершены успешно\n");
return 0;
}
}

View File

@@ -1,50 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c11 -g
all: server_udp_third client_udp_third
server_udp_third: server.c
$(CC) $(CFLAGS) -o $@ $<
client_udp_third: client.c
$(CC) $(CFLAGS) -o $@ $<
test_server: server_udp_third
@echo "=== Запуск UDP-сервера (каждый третий символ -> пробел) ==="
@echo "Выходной файл: out.txt"
./server_udp_third 5000 out.txt
test_client: client_udp_third
@echo "=== Запуск UDP-клиента ==="
@echo "Создаём input.txt"
@printf "abcdefghi\n1234567890\n" > input.txt
./client_udp_third 127.0.0.1 5000 input.txt
test_all: all
@echo "=== Автотест UDP (каждый третий символ -> пробел) ==="
@printf "abcdefghi\n1234567890\n" > input.txt
./server_udp_third 5000 out.txt & \
SRV=$$!; \
sleep 1; \
./client_udp_third 127.0.0.1 5000 input.txt; \
wait $$SRV; \
echo "--- input.txt ---"; \
cat input.txt; \
echo "--- out.txt ---"; \
cat out.txt
clean:
@echo "Очистка..."
rm -f server_udp_third client_udp_third
rm -f input.txt out.txt
help:
@echo "Targets:"
@echo " all - build server_udp_third and client_udp_third"
@echo " test_server - run server (port 5000, out.txt)"
@echo " test_client - run client to send input.txt"
@echo " test_all - end-to-end UDP test"
@echo " clean - remove binaries and test files"
@echo " help - show this help"
.PHONY: all test_server test_client test_all clean help

View File

@@ -1,117 +0,0 @@
// client_udp_third.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#define BUF_SIZE 4096
#define END_MARKER "END_OF_TRANSMISSION"
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr,
"Usage: %s <server_ip> <server_port> <input_file>\n",
argv[0]);
fprintf(stderr,
"Example: %s 127.0.0.1 5000 input.txt\n",
argv[0]);
return -1;
}
const char *server_ip = argv[1];
const char *server_port = argv[2];
const char *input_path = argv[3];
char *endptr = NULL;
errno = 0;
long port_long = strtol(server_port, &endptr, 10);
if (errno != 0 || endptr == server_port || *endptr != '\0' ||
port_long <= 0 || port_long > 65535) {
fprintf(stderr, "ERROR: invalid port '%s'\n", server_port);
return -1;
}
int port = (int) port_long;
FILE *fin = fopen(input_path, "r");
if (!fin) {
perror("fopen(input_file)");
return -1;
}
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
fclose(fin);
return -1;
}
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, server_ip, &servaddr.sin_addr) != 1) {
fprintf(stderr, "ERROR: invalid IP address '%s'\n", server_ip);
close(sockfd);
fclose(fin);
return -1;
}
char buf[BUF_SIZE];
for (;;) {
size_t n = fread(buf, 1, sizeof(buf), fin);
if (n > 0) {
ssize_t sent = sendto(sockfd,
buf,
n,
0,
(struct sockaddr *) &servaddr,
sizeof(servaddr));
if (sent < 0 || (size_t) sent != n) {
perror("sendto");
close(sockfd);
fclose(fin);
return -1;
}
}
if (n < sizeof(buf)) {
if (ferror(fin)) {
perror("fread");
close(sockfd);
fclose(fin);
return -1;
}
break;
}
}
if (fclose(fin) == EOF) {
perror("fclose(input_file)");
}
ssize_t sent = sendto(sockfd,
END_MARKER,
strlen(END_MARKER),
0,
(struct sockaddr *) &servaddr,
sizeof(servaddr));
if (sent < 0 || (size_t) sent != strlen(END_MARKER)) {
perror("sendto(END_MARKER)");
close(sockfd);
return -1;
}
printf("File '%s' sent to %s:%d, END marker transmitted.\n",
input_path, server_ip, port);
close(sockfd);
return 0;
}

View File

@@ -1,142 +0,0 @@
// server_udp_third.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#define BUF_SIZE 4096
#define END_MARKER "END_OF_TRANSMISSION"
static void process_block(char *buf,
ssize_t len,
long long *pos_counter,
long long *repl_counter) {
if (!buf || !pos_counter || !repl_counter) {
return;
}
for (ssize_t i = 0; i < len; i++) {
char c = buf[i];
long long pos = *pos_counter;
if (((pos + 1) % 3 == 0) && c != '\0') {
buf[i] = ' ';
(*repl_counter)++;
}
(*pos_counter)++;
}
}
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr,
"Usage: %s <port> <output_file>\n",
argv[0]);
fprintf(stderr,
"Example: %s 5000 out.txt\n",
argv[0]);
return -1;
}
char *endptr = NULL;
errno = 0;
long port_long = strtol(argv[1], &endptr, 10);
if (errno != 0 || endptr == argv[1] || *endptr != '\0' ||
port_long <= 0 || port_long > 65535) {
fprintf(stderr, "ERROR: invalid port '%s'\n", argv[1]);
return -1;
}
int port = (int) port_long;
const char *out_path = argv[2];
FILE *fout = fopen(out_path, "w");
if (!fout) {
perror("fopen(output_file)");
return -1;
}
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
fclose(fout);
return -1;
}
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
perror("bind");
close(sockfd);
fclose(fout);
return -1;
}
printf("UDP server (third-char) listening on port %d, output file: %s\n",
port, out_path);
char buf[BUF_SIZE];
long long pos_counter = 0;
long long repl_counter = 0;
int done = 0;
while (!done) {
struct sockaddr_in cliaddr;
socklen_t cli_len = sizeof(cliaddr);
ssize_t n = recvfrom(sockfd,
buf,
sizeof(buf) - 1,
0,
(struct sockaddr *) &cliaddr,
&cli_len);
if (n < 0) {
perror("recvfrom");
repl_counter = -1;
break;
}
buf[n] = '\0';
if (strcmp(buf, END_MARKER) == 0) {
printf("Received END marker from %s:%d, finishing.\n",
inet_ntoa(cliaddr.sin_addr),
ntohs(cliaddr.sin_port));
done = 1;
break;
}
process_block(buf, n, &pos_counter, &repl_counter);
if (fwrite(buf, 1, (size_t) n, fout) != (size_t) n) {
perror("fwrite");
repl_counter = -1;
done = 1;
break;
}
}
if (fclose(fout) == EOF) {
perror("fclose(output_file)");
repl_counter = -1;
}
close(sockfd);
printf("Total replacements (every 3rd char): %lld\n", repl_counter);
if (repl_counter < 0) {
return -1;
}
return 0;
}

View File

@@ -1,51 +0,0 @@
CC = gcc
CFLAGS = -Wall -Wextra -std=c11 -g
all: server_tcp_pairs client_tcp_pairs
server_tcp_pairs: server.c
$(CC) $(CFLAGS) -o $@ $<
client_tcp_pairs: client.c
$(CC) $(CFLAGS) -o $@ $<
test_server: server_tcp_pairs
@echo "=== Запуск TCP-сервера (пары одинаковых символов) ==="
@echo "Выходной файл: out.txt"
./server_tcp_pairs 5000 out.txt
test_client: client_tcp_pairs
@echo "=== Запуск TCP-клиента ==="
@echo "Создаём input.txt"
@printf "aabbccddeeff\nabba\nxxxxx\n" > input.txt
./client_tcp_pairs 127.0.0.1 5000 input.txt
test_all: all
@echo "=== Автотест TCP (пары одинаковых символов) ==="
@printf "aabbccddeeff\nabba\nxxxxx\n" > input.txt
./server_tcp_pairs 5000 out.txt & \
SRV=$$!; \
sleep 1; \
./client_tcp_pairs 127.0.0.1 5000 input.txt; \
wait $$SRV; \
echo "--- input.txt ---"; \
cat input.txt; \
echo "--- out.txt ---"; \
cat out.txt
clean:
@echo "Очистка..."
rm -f server_tcp_pairs client_tcp_pairs
rm -f input.txt out.txt
help:
@echo "Targets:"
@echo " all - build server_tcp_pairs and client_tcp_pairs"
@echo " test_server - run server (port 5000, out.txt)"
@echo " test_client - run client to send input.txt"
@echo " test_all - end-to-end TCP test"
@echo " clean - remove binaries and test files"
@echo " help - show this help"
.PHONY: all test_server test_client test_all clean help

View File

@@ -1,139 +0,0 @@
// client_tcp_pairs.c
// TCP-клиент для лабораторной №8, вариант "во всех парах одинаковых символов
// второй символ заменить на пробел".
// Клиент читает входной файл и передаёт его содержимое серверу по TCP.
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fread
#include <stdlib.h> // exit, EXIT_FAILURE, strtol
#include <string.h> // memset, strlen
#include <errno.h> // errno
#include <unistd.h> // close, write
#include <arpa/inet.h> // sockaddr_in, inet_pton, htons
#include <sys/socket.h> // socket, connect
#include <sys/types.h> // типы сокетов
#include <netinet/in.h> // sockaddr_in
#define BUF_SIZE 4096
int main(int argc, char *argv[])
{
// Ожидаемые аргументы:
// argv[1] - IP-адрес сервера (например, 127.0.0.1).
// argv[2] - порт сервера.
// argv[3] - путь к входному файлу.
if (argc < 4) {
fprintf(stderr,
"Usage: %s <server_ip> <server_port> <input_file>\n",
argv[0]);
fprintf(stderr,
"Example: %s 127.0.0.1 5000 input.txt\n",
argv[0]);
return -1;
}
const char *server_ip = argv[1];
const char *server_port = argv[2];
const char *input_path = argv[3];
// Разбор порта.
char *endptr = NULL;
errno = 0;
long port_long = strtol(server_port, &endptr, 10);
if (errno != 0 || endptr == server_port || *endptr != '\0' ||
port_long <= 0 || port_long > 65535) {
fprintf(stderr, "ERROR: invalid port '%s'\n", server_port);
return -1;
}
int port = (int)port_long;
// Открываем входной файл.
FILE *fin = fopen(input_path, "r");
if (!fin) {
perror("fopen(input_file)");
return -1;
}
// Создаём TCP-сокет.
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
fclose(fin);
return -1;
}
// Заполняем структуру адреса сервера.
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
// Переводим строковый IP в бинарную форму.
if (inet_pton(AF_INET, server_ip, &servaddr.sin_addr) != 1) {
fprintf(stderr, "ERROR: invalid IP address '%s'\n", server_ip);
close(sockfd);
fclose(fin);
return -1;
}
// Устанавливаем TCP-соединение.
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("connect");
close(sockfd);
fclose(fin);
return -1;
}
printf("Connected to %s:%d, sending file '%s'\n",
server_ip, port, input_path);
char buf[BUF_SIZE];
for (;;) {
// Читаем блок из файла.
size_t n = fread(buf, 1, sizeof(buf), fin);
if (n > 0) {
// Отправляем блок по TCP.
size_t sent_total = 0;
while (sent_total < n) {
ssize_t sent = write(sockfd,
buf + sent_total,
n - sent_total);
if (sent < 0) {
perror("write");
close(sockfd);
fclose(fin);
return -1;
}
sent_total += (size_t)sent;
}
}
// Если прочитали меньше, чем BUF_SIZE, либо EOF, либо ошибка.
if (n < sizeof(buf)) {
if (ferror(fin)) {
perror("fread");
close(sockfd);
fclose(fin);
return -1;
}
break; // EOF, передачу завершаем.
}
}
// Закрываем файл.
if (fclose(fin) == EOF) {
perror("fclose(input_file)");
}
// Корректно закрываем соединение, чтобы сервер получил EOF.
if (shutdown(sockfd, SHUT_WR) < 0) {
perror("shutdown");
}
close(sockfd);
printf("File '%s' sent to %s:%d, connection closed.\n",
input_path, server_ip, port);
return 0;
}

View File

@@ -1,189 +0,0 @@
// server_tcp_pairs.c
// Лабораторная №8, протокол TCP (нечётные варианты, но здесь по заданию TCP).
// Задача: во всех парах одинаковых символов второй символ заменить на пробел,
// считать количество замен и сохранить обработанный текст в выходной файл.
#include <stdio.h> // printf, fprintf, perror, FILE, fopen, fclose, fwrite
#include <stdlib.h> // exit, EXIT_FAILURE, strtol
#include <string.h> // memset, strlen
#include <errno.h> // errno
#include <unistd.h> // close, read, write
#include <arpa/inet.h> // sockaddr_in, inet_ntoa, htons, htonl, ntohs, ntohl
#include <sys/socket.h> // socket, bind, listen, accept
#include <sys/types.h> // типы сокетов
#include <netinet/in.h> // структура sockaddr_in
#define BUF_SIZE 4096 // Размер буфера приёма из TCP-сокета.
// Функция обрабатывает блок данных, заменяя во всех парах одинаковых подряд
// идущих символов второй символ пары на пробел. Пары могут пересекать границу
// буферов, поэтому учитывается последний символ предыдущего блока.
static void process_block_pairs(char *buf,
ssize_t len,
int *has_prev,
unsigned char *prev_char,
long long *repl_counter) {
if (!buf || !has_prev || !prev_char || !repl_counter) {
return; // Проверка входных указателей.
}
for (ssize_t i = 0; i < len; i++) {
unsigned char c = (unsigned char) buf[i];
if (*has_prev) {
// Есть предыдущий символ из этого же потока.
if (c == *prev_char) {
// Найдена пара одинаковых подряд символов.
buf[i] = ' '; // Заменяем второй символ пары на пробел.
(*repl_counter)++; // Увеличиваем счётчик замен.
}
*has_prev = 0; // Сбрасываем флаг: пара уже обработана.
} else {
// Текущий символ станет предыдущим для возможной пары в следующем байте.
*prev_char = c;
*has_prev = 1;
}
}
}
int main(int argc, char *argv[]) {
// Ожидаемые аргументы:
// argv[1] - порт TCP сервера (например, 5000).
// argv[2] - имя выходного файла.
if (argc < 3) {
fprintf(stderr,
"Usage: %s <port> <output_file>\n",
argv[0]);
fprintf(stderr,
"Example: %s 5000 out.txt\n",
argv[0]);
return -1;
}
// Разбор номера порта.
char *endptr = NULL;
errno = 0;
long port_long = strtol(argv[1], &endptr, 10);
if (errno != 0 || endptr == argv[1] || *endptr != '\0' ||
port_long <= 0 || port_long > 65535) {
fprintf(stderr, "ERROR: invalid port '%s'\n", argv[1]);
return -1;
}
int port = (int) port_long;
const char *out_path = argv[2];
// Открываем выходной файл для записи (перезаписываем).
FILE *fout = fopen(out_path, "w");
if (!fout) {
perror("fopen(output_file)");
return -1;
}
// Создаём TCP-сокет.
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror("socket");
fclose(fout);
return -1;
}
// Включаем SO_REUSEADDR, чтобы можно было быстро перезапускать сервер.
int optval = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
&optval, sizeof(optval)) < 0) {
perror("setsockopt(SO_REUSEADDR)");
close(listen_fd);
fclose(fout);
return -1;
}
// Заполняем структуру адреса сервера.
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // Принимать на всех интерфейсах.
servaddr.sin_port = htons(port);
// Привязываем сокет к адресу и порту.
if (bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
perror("bind");
close(listen_fd);
fclose(fout);
return -1;
}
// Переводим сокет в режим прослушивания.
if (listen(listen_fd, 1) < 0) {
perror("listen");
close(listen_fd);
fclose(fout);
return -1;
}
printf("TCP server (pairs) listening on port %d, output file: %s\n",
port, out_path);
// Принимаем одно соединение от клиента.
struct sockaddr_in cliaddr;
socklen_t cli_len = sizeof(cliaddr);
int conn_fd = accept(listen_fd, (struct sockaddr *) &cliaddr, &cli_len);
if (conn_fd < 0) {
perror("accept");
close(listen_fd);
fclose(fout);
return -1;
}
printf("Client connected from %s:%d\n",
inet_ntoa(cliaddr.sin_addr),
ntohs(cliaddr.sin_port));
close(listen_fd); // Больше новых клиентов не принимаем.
char buf[BUF_SIZE];
long long repl_counter = 0; // Общее количество замен.
int has_prev = 0; // Был ли предыдущий символ для пары.
unsigned char prev_char = 0; // Предыдущий символ, если has_prev == 1.
for (;;) {
// Считываем данные из TCP-сокета.
ssize_t n = read(conn_fd, buf, sizeof(buf));
if (n > 0) {
// Обрабатываем блок на предмет пар одинаковых символов.
process_block_pairs(buf, n, &has_prev, &prev_char, &repl_counter);
// Пишем обработанный блок в выходной файл.
if (fwrite(buf, 1, (size_t) n, fout) != (size_t) n) {
perror("fwrite");
repl_counter = -1;
break;
}
} else if (n == 0) {
// Клиент корректно закрыл соединение.
printf("Client disconnected.\n");
break;
} else {
// Ошибка при чтении.
perror("read");
repl_counter = -1;
break;
}
}
// Закрываем соединение.
close(conn_fd);
// Закрываем файл.
if (fclose(fout) == EOF) {
perror("fclose(output_file)");
repl_counter = -1;
}
printf("Total replacements (pairs): %lld\n", repl_counter);
if (repl_counter < 0) {
return -1;
}
return 0;
}