lab4 added

This commit is contained in:
2026-11-11 13:34:01 +06:00
parent 42cf4ca883
commit da8398c9ab
6 changed files with 349 additions and 0 deletions
+121
View File
@@ -0,0 +1,121 @@
int main()
{
// Инициализация ncurses
initscr();
cbreak();
noecho();
curs_set(0);
if (has_colors())
{
start_color();
use_default_colors();
init_pair(1, COLOR_CYAN, -1);
init_pair(2, COLOR_GREEN, -1);
init_pair(3, COLOR_YELLOW, -1);
init_pair(4, COLOR_RED, -1);
}
// Открытие файла
int fd = open("data.txt", O_RDWR);
if (fd == -1)
{
string message = "Ошибка открытия файла data.txt";
showMessage(message, 4);
napms(2500);
endwin();
cerr << "Ошибка: " << strerror(errno) << '\n';
return 1;
}
// Подготовка блокировки всего файла
struct flock lock{};
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
// Попытка установить блокировку без ожидания
if (fcntl(fd, F_SETLK, &lock) == -1)
{
if (errno == EACCES || errno == EAGAIN)
{
showMessage("Файл заблокирован. Ожидание...", 3);
napms(1000);
// Установка блокировки с ожиданием
while (fcntl(fd, F_SETLKW, &lock) == -1)
{
if (errno == EINTR)
continue;
string message = "Ошибка ожидания блокировки";
showMessage(message, 4);
napms(2500);
close(fd);
endwin();
return 1;
}
}
else
{
showMessage("Ошибка установки блокировки", 4);
napms(2500);
close(fd);
endwin();
return 1;
}
}
// Блокировка успешно получена
showMessage("Блокировка установлена", 2);
napms(1000);
// Чтение файла
if (!readFile(fd))
{
showMessage("Ошибка чтения файла", 4);
napms(2500);
lock.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &lock);
close(fd);
endwin();
return 1;
}
// Ожидание в течение 7 секунд
napms(7000);
// Снятие блокировки
lock.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &lock) == -1)
{
showMessage("Ошибка снятия блокировки", 4);
napms(2500);
close(fd);
endwin();
return 1;
}
showMessage("Блокировка снята", 2);
napms(1500);
// Закрытие файла и завершение ncurses
close(fd);
endwin();
return 0;
}