Проектирование гипотетической операционной системы
Создание эмулятора, демонстрирующего работу файловой системы и планировщика процессов разработанной операционной системы. Виртуальные страницы, системные вызовы и способы организации файлов. Команды для работы с процессами в операционной системе.
| Рубрика | Программирование, компьютеры и кибернетика |
| Вид | курсовая работа |
| Язык | русский |
| Дата добавления | 02.12.2012 |
| Размер файла | 3,1 M |
Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже
Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.
bw.Write(fs_info);
bw.Write(sb.cl_size);
bw.Write(sb.sb_fst_cl);
bw.Write(sb.fat_fst_cl);
bw.Write(sb.cp_fst_cl);
bw.Write(sb.usr_fst_cl);
bw.Write(sb.rt_fst_cl);
bw.Write(sb.f_fst_cl);
bw.Write(sb.f_cl_ct);
bw.Write(sb.max_usr_ct);
bw.Close();
}
public void SaveFAT()
{
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
bw.BaseStream.Seek((FAT_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
bw.Write(fat_table[i]);
}
bw.Close();
}
public void SaveCopyFAT()
{
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
bw.BaseStream.Seek((COPY_FAT_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
bw.Write(fat_cp_table[i]);
}
bw.Close();
}
public void SaveUserTable()
{
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
bw.BaseStream.Seek((USERS_TABLE_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
for (int i = 0; i < MAX_USERS_COUNT; i++)
{
if (usr_table[i].name != null)
{
bw.Write(usr_table[i].uid);
char[] name = new char[LOGIN_LENGTH];
usr_table[i].name.CopyTo(0, name, 0, usr_table[i].name.Length);
bw.Write(name);
bw.Write(usr_table[i].gid);
char[] group = new char[GROUP_NAME_LENGTH];
usr_table[i].group_name.CopyTo(0, group, 0, usr_table[i].group_name.Length);
bw.Write(group);
char[] pass = new char[PASSWORD_LENGTH];
usr_table[i].password_hash.CopyTo(0, pass, 0, usr_table[i].password_hash.Length);
bw.Write(pass);
bw.Write(usr_table[i].orders);
}
}
bw.Close();
}
public void SaveRoot()
{
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
bw.BaseStream.Seek((ROOT_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
for (int i = 0; i < root.Length; i++)
{
if (root[i].file_name != null)
{
char[] file_name = new char[FILE_NAME_LENGTH];
root[i].file_name.CopyTo(0, file_name, 0, root[i].file_name.Length);
bw.Write(file_name);
char[] ext = new char[FILE_EXT_LENGTH];
root[i].ext.CopyTo(0, ext, 0, root[i].ext.Length);
bw.Write(ext);
char[] date = new char[DATE_LENGTH];
root[i].last_data.CopyTo(0, date, 0, root[i].last_data.Length);
bw.Write(date);
bw.Write(root[i].ft_cl);
bw.Write(root[i].size);
char[] orders = new char[FILE_ORDERS_LENGTH];
root[i].file_orders.CopyTo(0, orders, 0, root[i].file_orders.Length);
bw.Write(orders);
}
else if (root[i].file_name == null)
{
for (int j = 0; j < FILE_NAME_LENGTH-1; j++)
{
bw.Write(Convert.ToByte(0));
}
for (int j = 0; j < FILE_EXT_LENGTH-1; j++)
{
bw.Write(Convert.ToByte(0));
}
for (int j = 0; j < DATE_LENGTH-1; j++)
{
bw.Write(Convert.ToByte(0));
}
bw.Write(0);
for (int j = 0; j < FILE_ORDERS_LENGTH-1; j++)
{
bw.Write(Convert.ToByte(0));
}
}
}
bw.Close();
}
#endregion
#region IncreaseMethods
public void IncreaseLength(ref int[] arr, int delta)
{
int[] tmp = new int[arr.Length + delta];
Array.Copy(arr, 0, tmp, 0, arr.Length);
arr = tmp;
}
public void IncreaseLengthRoot(ref File[] arr, int delta)
{
File[] tmp = new File[arr.Length + delta];
Array.Copy(arr, 0, tmp, 0, arr.Length);
arr = tmp;
}
#endregion
}
}
SupportCalls.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace NFOS.FileSystem
{
class SupportCalls
{
NFOS.FileSystem.SystemCalls sc = new FileSystem.SystemCalls();
Emul emul = new Emul();
public bool DefinitionLine(string line, FileSystem.Structures str, char orders)
{
Thread disp = new Thread(new ThreadStart(emul.disprun)); //запускаем диспетчер
disp.Start();
string[] sp_line = line.Split(' ');
#region fsinfo
if ((sp_line[0] == "fsinfo") && (sp_line.Length == 1)) /////////fsinfo
{
sc.FSInfo(str);
return false;
}
#endregion
#region format
else if ((sp_line[0] == "format") && (sp_line.Length == 1))
{
sc.Formatting();
return true;
}
#endregion
#region ps
else if ((sp_line[0] == "ps") && (sp_line.Length == 1)) //список процессов
{
emul.flag = false;
emul.print();
emul.flag = true;
return false;
}
#endregion
#region addpr
else if ((sp_line[0] == "addpr") && (sp_line.Length == 1)) //список процессов
{
emul.flag = false;
emul.CreateProc();
emul.flag = true;
return false;
}
#endregion
#region chgpr
else if ((sp_line[0] == "chgpr") && (sp_line.Length == 1)) //список процессов
{
emul.flag = false;
emul.chgpr();
emul.flag = true;
return false;
}
#endregion
#region delpr
else if ((sp_line[0] == "delpr") && (sp_line.Length == 1)) //список процессов
{
emul.flag = false;
emul.KillProc();
emul.flag = true;
return false;
}
#endregion
#region klall
else if ((sp_line[0] == "klall") && (sp_line.Length == 1)) //список процессов
{
emul.flag = false;
emul.killall();
emul.flag = true;
return false;
}
#endregion
#region help
else if ((sp_line[0] == "help") && (sp_line.Length == 1))
{
sc.Help();
return false;
}
#endregion
#region cr
else if ((sp_line[0] == "cr") && (sp_line.Length > 1)) ////////////cr -f file.txt
{
#region -f
if (sp_line[1] == "-f")
{
if (sp_line.Length == 3)
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1]!=""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
sc.CreateFile(sp_again[0], sp_again[1], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
}
#endregion
#region -u
else if (sp_line[1] == "-u")
{
if (sp_line.Length == 6)
{
if ((sp_line[2].Length <= 10) && (sp_line[3].Length <= 2) && (sp_line[4].Length <= 10) && (sp_line[5] != ""))
{
if ((sp_line[5] == "g") || (sp_line[5] == "o"))
{
sc.CreateUser(sp_line[2], Convert.ToUInt16(sp_line[3]), sp_line[4], Convert.ToChar(sp_line[5]), orders, str);
}
else
{
Console.WriteLine("Права пользователя могут быть g - группа, o - другие");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
#endregion
return false;
}
#endregion
#region rn
else if ((sp_line[0] == "rn") && (sp_line.Length > 1))
{
if (sp_line.Length == 3)
{
string[] sp_again = sp_line[1].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) || (sp_again[1].Length <= 3))
{
sc.RenameFile(sp_again[0], sp_again[1], sp_line[2], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
return false;
}
#endregion
#region rm
else if ((sp_line[0] == "rm") && (sp_line.Length > 1))
{
if (sp_line[1] == "-f")
{
if ((sp_line.Length == 3) && (sp_line[2] != ""))
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
sc.RemoveFile(sp_again[0], sp_again[1], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else if (sp_line[1] == "-u")
{
if ((sp_line.Length == 3) && (sp_line[2] != ""))
{
sc.RemoveUser(Convert.ToUInt16(sp_line[2]), str, orders);
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
return false;
}
#endregion
#region show
else if ((sp_line[0] == "show") && (sp_line.Length > 1))
{
#region -f
if (sp_line[1] == "-f")
{
if (sp_line.Length == 2)
{
if (sp_line[1] != "")
{
sc.ShowFiles(str);
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
#region -F
else if (sp_line[1] == "-F")
{
if (sp_line.Length == 2)
{
if (sp_line[1] != "")
{
sc.ShowFilesLong(str);
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
#region -u
else if (sp_line[1] == "-u")
{
if (sp_line.Length == 2)
{
if (sp_line[1] != "")
{
sc.ShowUsers(str);
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
else
{
Console.WriteLine("Неправильный синтаксис.");
}
return false;
}
#endregion
#region chmod
else if ((sp_line[0] == "chmod") && (sp_line.Length > 1))
{
#region -o
if (sp_line[1] == "-o")
{
if ((sp_line.Length == 4) && (sp_line[3] != ""))
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
sc.ChModOther(sp_again[0], sp_again[1], sp_line[3], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
#region -g
else if (sp_line[1] == "-g")
{
if ((sp_line.Length == 4) && (sp_line[3] != ""))
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
sc.ChModGroup(sp_again[0], sp_again[1], sp_line[3], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
#region -u
else if (sp_line[1] == "-u")
{
if ((sp_line.Length == 4) && (sp_line[3] != ""))
{
if ((sp_line[3] == "a") || (sp_line[3] == "g") || (sp_line[3] == "o"))
{
sc.ChOrders(Convert.ToUInt16(sp_line[2]), Convert.ToChar(sp_line[3]), str, orders);
}
else
{
Console.WriteLine("Права не правильно заданы.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
#endregion
return false;
}
#endregion
#region wr
else if ((sp_line[0] == "wr") && (sp_line.Length > 1))
{
#region -t
if (sp_line[1] == "-t")
{
if (sp_line.Length == 3)
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
Console.WriteLine("Введите содержание файла (для окончания ввода введите <end>)");
string one_line = "";
string text = "";
while (one_line != "<end>")
{
one_line = Console.ReadLine();
if (one_line != "<end>")
{
text += one_line + "<n>";
}
}
sc.OpenTruncate(sp_again[0], sp_again[1], text, str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
}
#endregion
#region -a
else if (sp_line[1] == "-a")
{
if (sp_line.Length == 3)
{
string[] sp_again = sp_line[2].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
Console.WriteLine("Введите текст, который хотите добавит к файлу (для окончания ввода введите <end>)");
string one_line = "";
string text = "";
while (one_line != "<end>")
{
one_line = Console.ReadLine();
if (one_line != "<end>")
{
text += one_line + "<n>";
}
}
sc.OpenAppend(sp_again[0], sp_again[1], text, str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
}
#endregion
else
{
Console.WriteLine("Неправильный синтаксис.");
}
return false;
}
#endregion
#region text
else if ((sp_line[0] == "text") && (sp_line.Length > 1))
{
if (sp_line.Length == 2)
{
string[] sp_again = sp_line[1].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
sc.ShowFileText(sp_again[0], sp_again[1], str, orders);
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
return false;
}
#endregion
#region cp
else if ((sp_line[0] == "cp") && (sp_line.Length > 1))
{
if (sp_line.Length == 3)
{
string[] sp_again = sp_line[1].Split('.');
if ((sp_again.Length == 2) && (sp_again[1] != ""))
{
if ((sp_again[0].Length <= 10) && (sp_again[1].Length <= 3))
{
if (sp_line[2].Length <= 10)
{
sc.CopyFile(sp_again[0], sp_again[1], sp_line[2], str, orders);
}
else
{
Console.WriteLine("Имя копии слишком длинное.");
}
}
else
{
Console.WriteLine("Имя либо расширение слишком длинное.");
}
}
else
{
Console.WriteLine("Неправильный синтаксис.");
}
}
else
Console.WriteLine("Неправильный синтаксис.");
return false;
}
#endregion
else if (line != "")
{
Console.WriteLine("Неправильный синтаксис.");
return false;
}
else
{
return false;
}
}
}
}
SystemCalls.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
namespace NFOS.FileSystem
{
class SystemCalls
{
#region Constants
/*Название файловой системы*/
private const string FS_NAME_STR = "NFFS";
/*Длина имени файловой системы*/
private const ushort FS_NAME_LENGTH = 10;
/*Размер кластера*/
private const ushort CLUSTER_SIZE = 512;
/*Начальный кластер суперблока*/
public const ushort SUPERBLOCK_FIRST_CLUSTER = 1;
/*Начальный кластер FAT*/
public const ushort FAT_FIRST_CLUSTER = 2;
/*Начальный кластер Копии FAT*/
public const ushort COPY_FAT_FIRST_CLUSTER = 4;
/*Начальный кластер таблицы юзеров*/
public const ushort USERS_TABLE_FIRST_CLUSTER = 6;
/*Начальный кластер корневого каталога*/
public const ushort ROOT_FIRST_CLUSTER = 9;
/*Начальный кластер области файлов*/
public const ushort FILES_FIRST_CLUSTER = 53;
/*Количество кластеров*/
private const ushort CLUSTERS_COUNT = 512;
/*Максимальное количество пользователей*/
private const ushort MAX_USERS_COUNT = 20;
/*Размер корневого каталога*/
private const ushort ROOT_LENGTH = 22528;
/*Путь к логическому диску ФС*/
private const string PATH = "../../Resources/FS.bin";
/*Идентификатор пользователя*/
private const ushort ADMIN_UID = 1;
/*Логин учетной записи администратора после форматирования*/
private const string ADMIN_NAME = "admin";
/*Длина логина учетной записи*/
private const ushort LOGIN_LENGTH = 10;
/*Пароль учетной записи администратора после форматирования в хеш*/
private const string ADMIN_PASSWORD_HASH = "21232f297a57a5a743894a0e4a801fc3";
/*Длина пароля учетной записи*/
private const ushort PASSWORD_LENGTH = 32;
/*Идентификатор группы учетной записи*/
private const ushort ADMIN_GID = 1;
/*Имя группы администратора после форматирования*/
private const string ADMIN_GROUP_NAME = "admin";
/*Длина имени группы учетной записи*/
private const ushort GROUP_NAME_LENGTH = 10;
/*Права администратора*/
private const string ADMIN_ORDERS = "a";
/*Длина прав*/
private const ushort ORDERS_LENGTH = 1;
/*Длина имени файла*/
private const ushort FILE_NAME_LENGTH = 10;
/*Длина расширения файла*/
private const ushort FILE_EXT_LENGTH = 3;
/*Длина даты создания или последнего изменения файла*/
private const ushort DATE_LENGTH = 19;
/*Длина прав доступа к файлу*/
private const ushort FILE_ORDERS_LENGTH = 6;
#endregion
#region Прочие системные вызовы
/// <summary>
/// Форматирование диска
/// </summary>
public void Formatting()
{
BinaryWriter bw = new BinaryWriter(File.Open(PATH, FileMode.Create));
/*Создание суперблока*/
bw.BaseStream.Seek((SUPERBLOCK_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
char[] fs_info = new char[FS_NAME_LENGTH];
FS_NAME_STR.CopyTo(0, fs_info, 0, FS_NAME_STR.Length);
bw.Write(fs_info);
bw.Write(CLUSTER_SIZE);
bw.Write(SUPERBLOCK_FIRST_CLUSTER);
bw.Write(FAT_FIRST_CLUSTER);
bw.Write(COPY_FAT_FIRST_CLUSTER);
bw.Write(USERS_TABLE_FIRST_CLUSTER);
bw.Write(ROOT_FIRST_CLUSTER);
bw.Write(FILES_FIRST_CLUSTER);
bw.Write(CLUSTERS_COUNT);
bw.Write(MAX_USERS_COUNT);
/*Создание FAT*/
bw.BaseStream.Seek((FAT_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
ushort value = 0;
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
bw.Write(value);
}
/*Создание Копии FAT*/
bw.BaseStream.Seek((COPY_FAT_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
bw.Write(value);
}
/*Создание таблицы пользователей*/
bw.BaseStream.Seek((USERS_TABLE_FIRST_CLUSTER - 1) * CLUSTER_SIZE, SeekOrigin.Begin);
char[] admin_name = new char[LOGIN_LENGTH];
ADMIN_NAME.CopyTo(0, admin_name, 0, ADMIN_NAME.Length);
char[] admin_group = new char[GROUP_NAME_LENGTH];
ADMIN_GROUP_NAME.CopyTo(0, admin_group, 0, ADMIN_GROUP_NAME.Length);
char[] admin_password_hash = new char[PASSWORD_LENGTH];
ADMIN_PASSWORD_HASH.CopyTo(0, admin_password_hash, 0, ADMIN_PASSWORD_HASH.Length);
char[] admin_orders = new char[ORDERS_LENGTH];
ADMIN_ORDERS.CopyTo(0, admin_orders, 0, ADMIN_ORDERS.Length);
/*Создание администратора*/
bw.Write(ADMIN_UID);
bw.Write(admin_name);
bw.Write(ADMIN_GID);
bw.Write(admin_group);
bw.Write(admin_password_hash);
bw.Write(admin_orders);
/*Создание пустых учетных записей*/
ushort id = 0;
char[] name = new char[10];
char[] password = new char[32];
char orders = ' ';
for (int i = 0; i < MAX_USERS_COUNT - 1; i++)
{
bw.Write(id);
bw.Write(name);
bw.Write(id);
bw.Write(name);
bw.Write(password);
bw.Write(orders);
}
/*Создание корневого каталога*/
bw.BaseStream.Seek(((ROOT_FIRST_CLUSTER - 1) * CLUSTER_SIZE), SeekOrigin.Begin);
byte b = 0;
for (int i = 0; i < ROOT_LENGTH; i++)
{
bw.Write(b);
}
/*Создание области файлов*/
bw.BaseStream.Seek(((FILES_FIRST_CLUSTER - 1) * CLUSTER_SIZE), SeekOrigin.Begin);
for (int i = 0; i < CLUSTERS_COUNT * CLUSTER_SIZE; i++)
{
bw.Write(b);
}
bw.Close();
}
/// <summary>
/// Информация о файловой системе
/// </summary>
/// <param name="str"></param>
public void FSInfo(NFOS.FileSystem.Structures str)
{
Console.WriteLine("Имя файловой системы: "+str.sb.fs_name);
Console.WriteLine("Размер кластера: " + str.sb.cl_size);
Console.WriteLine("Первый кластер суперблока: " + str.sb.sb_fst_cl);
Console.WriteLine("Первый кластер FAT-таблицы: " + str.sb.fat_fst_cl);
Console.WriteLine("Первый кластер копии FAT-таблицы: " + str.sb.cp_fst_cl);
Console.WriteLine("Первый кластер таблицы пользователей: " + str.sb.usr_fst_cl);
Console.WriteLine("Первый кластер корневого каталога: " + str.sb.rt_fst_cl);
Console.WriteLine("Первый кластер области файлов: " + str.sb.f_fst_cl);
Console.WriteLine("Количество кластеров, выделенных под область файлов: " + str.sb.f_cl_ct);
Console.WriteLine("Максимальное количество пользователей: " + str.sb.max_usr_ct);
}
public void Help()
{
Console.WriteLine("Команды для работы:");
Console.WriteLine("fsinfo - Вывод информации о файловой системе.");
Console.WriteLine("help - Вывод справки.");
Console.WriteLine("exit - Выход из сисемы.");
Console.WriteLine("format - Форматирование логического диска.");
Console.WriteLine("show [-f][-F][-u] - Вывод информации.");
Console.WriteLine(" [-f] - Вывод всех файлов.");
Console.WriteLine(" [-F] - Вывод всех файлов в длинном формате.");
Console.WriteLine(" [-u] - Вывод всех существующих пользователей.");
Console.WriteLine("cr [-f][-u] - Создание.");
Console.WriteLine(" [-f] file.txt - Cоздание файла.");
Console.WriteLine(" [-u] name gid password orders - Создание пользователя.");
Console.WriteLine("wr [-t][-a] - Запись в файл.");
Console.WriteLine(" [-t] file.txt - Перезапись файла.");
Console.WriteLine(" [-a] file.txt - Допись в конец файла.");
Console.WriteLine("rm [-f][-u] - Удаление.");
Console.WriteLine(" [-f] file.txt - Удаление файла.");
Console.WriteLine(" [-u] uid - Удаление пользователя.");
Console.WriteLine("rn file.txt new_name - Переименование файла");
Console.WriteLine("cp file.txt copy_name - Копирование файла.");
Console.WriteLine("text file.txt - Просмотр содержимого файла");
Console.WriteLine("chmod [-o][-g][-u] - Изменение прав.");
Console.WriteLine(" [-o] file.txt rwx - Изменение прав доступа к файлу для других.");
Console.WriteLine(" [-g] file.txt rwx - Изменение прав доступа к файлу для группы.");
Console.WriteLine(" [-u] uid orders - Изменение прав пользователя.");
}
#endregion
#region Системные вызовы для работы с файлами
/// <summary>
/// Создание нового файла
/// </summary>
/// <param name="name"></param>
/// <param name="ext"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void CreateFile(string name, string ext, NFOS.FileSystem.Structures str, char orders)
{
int condition = 0;
bool full = true;
bool exist = false;
for (int i = 0; i < str.sb.f_cl_ct; i++)
{
if (str.fat_table[i] == 0)
{
full = false;
break;
}
}
for (int i = 0; i < str.root.Length; i++)
{
if (str.root[i].file_name == name)
{
exist = true;
break;
}
}
if (exist)
{
condition = 0;
}
else if (full)
{
condition = -1;
}
else if ((!exist) && (!full))
{
condition = 1;
}
/*Можно попробовать реализовать кейсом*/
if (condition == 0)
{
Console.WriteLine("Файл уже существует.");
}
else if (condition == -1)
{
Console.WriteLine("Недостаточно дискового пространства");
}
else if (condition == 1)
{
ushort first_cluster = 0; //переменная запоминает начальный кластер файла
/*Изменяем значения FAT и копии*/
for (ushort i = 0; i < str.sb.f_cl_ct; i++)
{
if (str.fat_table[i] == 0)
{
str.fat_table[i] = 999;
first_cluster = Convert.ToUInt16(i+1);
str.fat_cp_table = str.fat_table;
str.SaveFAT();
str.SaveCopyFAT();
break;
}
}
/*Изменяем значения корневого каталога*/
str.IncreaseLengthRoot(ref str.root, 1);
for (int i = 0; i < str.root.Length; i++)
{
if (str.root[i].file_name == null)
{
str.root[i].file_name = name;
str.root[i].ext = ext;
str.root[i].last_data = DateTime.Now.ToString();
str.root[i].ft_cl = first_cluster;
str.root[i].size = 0;
if (orders == 'a')
str.root[i].file_orders = "r-r-";
else if (orders == 'g')
str.root[i].file_orders = "rwxr-";
else if (orders == 'o')
str.root[i].file_orders = "rwxrwx";
str.SaveRoot();
break;
}
}
}
}
/// <summary>
/// Переименование файла
/// </summary>
/// <param name="old_name"></param>
/// <param name="ext"></param>
/// <param name="new_name"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void RenameFile(string old_name, string ext, string new_name, NFOS.FileSystem.Structures str, char orders)
{
int condition = 0;
bool exist_old = false;
bool exist_new = false;
for (int i = 0; i < str.root.Length; i++)
{
if ((str.root[i].file_name == new_name) && (str.root[i].ext == ext))
{
exist_new = true;
break;
}
if ((str.root[i].file_name == old_name) && (str.root[i].ext == ext))
{
exist_old = true;
char[] order = new char[FILE_ORDERS_LENGTH];
str.root[i].file_orders.CopyTo(0, order, 0, str.root[i].file_orders.Length);
if (((orders == 'g') && (order[1] != 'w')) || ((orders == 'o') && (order[4] != 'w')))
{
condition = -2;
}
}
}
if (exist_new)
{
condition = 0;
}
else if (!exist_old)
{
condition = -1;
}
else if (condition != -2)
{
condition = 1;
}
if (condition == -1)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == 0)
{
Console.WriteLine("Файл с таким именем уже существует.");
}
else if (condition == -2)
{
Console.WriteLine("Ваши права не позволяют переименовать этот файл");
}
else if (condition == 1)
{
for (int i = 0; i < str.root.Length; i++)
{
if (str.root[i].file_name == old_name)
{
str.root[i].file_name = new_name;
str.root[i].last_data = DateTime.Now.ToString();
str.root[i].size = 0;
str.SaveRoot();
break;
}
}
}
}
/// <summary>
/// Выводит список существующих файлов
/// </summary>
/// <param name="str"></param>
public void ShowFiles(NFOS.FileSystem.Structures str)
{
Console.WriteLine();
for (int i = 0; i < str.root.Length; i++)
{
if (str.root[i].file_name != null)
{
Console.Write(str.root[i].file_name + "." + str.root[i].ext + " ");
}
}
Console.WriteLine();
Console.WriteLine();
}
/// <summary>
/// Выводит список существующих файлов в длинном формате
/// </summary>
/// <param name="str"></param>
public void ShowFilesLong(NFOS.FileSystem.Structures str)
{
Console.WriteLine();
for (int i = 0; i < str.root.Length; i++)
{
if (str.root[i].file_name != null)
{
Console.WriteLine(str.root[i].file_name + "." + str.root[i].ext + " " + str.root[i].last_data + " " + str.root[i].size + "байт " + str.root[i].file_orders);
}
}
Console.WriteLine();
}
/// <summary>
/// Просмотр содержимого файла
/// </summary>
/// <param name="filename"></param>
/// <param name="ext"></param>
/// <param name="str"></param>
/// <param name="user_orders"></param>
public void ShowFileText(string filename, string ext, NFOS.FileSystem.Structures str, char user_orders)
{
int condition = 0;
bool exist = false;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
exist = true;
ind = i;
break;
}
}
if (exist)
{
if (user_orders == 'a')
{
condition = 1;
}
else if (user_orders == 'g')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[0] == 'r')
{
condition = 1;
}
else
{
condition = -1;
}
}
else if (user_orders == 'o')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[3] == 'r')
{
condition = 1;
}
else
{
condition = -1;
}
}
}
if (condition == 0)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют просматривать содержимое данного файла.");
}
else if (condition == 1)
{
int record = 0;
int cluster_full = 0;
int prev_cluster_ind = str.root[ind].ft_cl;
string text = "";
bool end = false;
BinaryReader br = new BinaryReader(System.IO.File.Open(PATH, FileMode.Open));
while (!end)
{
br.BaseStream.Seek((((FILES_FIRST_CLUSTER - 2) + prev_cluster_ind) * CLUSTER_SIZE) + cluster_full, SeekOrigin.Begin);
if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] != 999))
{
prev_cluster_ind = str.fat_table[prev_cluster_ind - 1];
cluster_full = 0;
}
else if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] == 999))
{
end = true;
}
text += Convert.ToString(br.ReadChar());
record++;
cluster_full++;
}
br.Close();
/*Разбираем строку*/
string[] sp_text = Regex.Split(text, "<n>");
for (int i = 0; i < sp_text.Length-1; i++)
{
Console.WriteLine(sp_text[i]);
}
}
}
/// <summary>
/// Перезапись файла
/// </summary>
/// <param name="filename"></param>
/// <param name="ext"></param>
/// <param name="text"></param>
/// <param name="str"></param>
/// <param name="user_orders"></param>
public void OpenTruncate(string filename, string ext, string text, NFOS.FileSystem.Structures str, char user_orders)
{
int condition = 0;
bool exist = false;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
exist = true;
ind = i;
break;
}
}
if (exist)
{
if (user_orders == 'a')
{
condition = 1;
}
else if (user_orders == 'g')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[1] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
else if (user_orders == 'o')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[4] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
}
if (condition == 0)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют производить записи в данный файл.");
}
else if (condition == 1)
{
/*Зачищаем кластеры в FAT*/
if (str.fat_table[str.root[ind].ft_cl - 1] != 999)
{
int i = str.root[ind].ft_cl - 1;
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
while (str.fat_table[i] != 999)
{
bw.BaseStream.Seek((((FILES_FIRST_CLUSTER - 1) + i) * CLUSTER_SIZE), SeekOrigin.Begin);
for (int k = 0; k < CLUSTERS_COUNT; k++)
{
bw.Write('\0');
}
int j = str.fat_table[i] - 1;
if (i == str.root[ind].ft_cl - 1)
{
str.fat_table[i] = 999;
}
else
{
str.fat_table[i] = 0;
}
i = j;
}
bw.BaseStream.Seek((((FILES_FIRST_CLUSTER - 1) + i) * CLUSTER_SIZE), SeekOrigin.Begin);
for (int k = 0; k < CLUSTERS_COUNT; k++)
{
bw.Write('\0');
}
str.fat_table[i] = 0;
bw.Close();
}
/*Разбираем строку*/
char[] char_text = new char[text.Length];
text.CopyTo(0, char_text, 0, text.Length);
int record = 0;
int cluster_full = 0;
int prev_cluster_ind = str.root[ind].ft_cl;
int index = 0;
BinaryWriter bw1 = new BinaryWriter(System.IO.File.OpenWrite(PATH));
while (record != char_text.Length)
{
bw1.BaseStream.Seek((((FILES_FIRST_CLUSTER - 2) + prev_cluster_ind) * CLUSTER_SIZE) + cluster_full, SeekOrigin.Begin);
/*Если кластер заполнен*/
if (cluster_full == CLUSTER_SIZE)
{
/*Поиск пустого кластера*/
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
if (str.fat_table[i] == 0)
{
str.fat_table[prev_cluster_ind - 1] = Convert.ToUInt16(i + 1);
str.fat_table[i] = 999;
prev_cluster_ind = i + 1;
cluster_full = 0;
break;
}
}
/*Если места нет*/
if (cluster_full != 0)
{
Console.WriteLine("Не хватает места на логическом диске. Введенная информация будет урезана.");
record++;
break;
}
}
bw1.Write(char_text[index]);
cluster_full++;
index++;
record++;
}
bw1.Close();
str.root[ind].last_data = DateTime.Now.ToString();
str.root[ind].size = record;
str.fat_cp_table = str.fat_table;
str.SaveFAT();
str.SaveCopyFAT();
str.SaveRoot();
}
}
/// <summary>
/// Допись в конец файла
/// </summary>
/// <param name="filename"></param>
/// <param name="ext"></param>
/// <param name="text"></param>
/// <param name="str"></param>
/// <param name="user_orders"></param>
public void OpenAppend(string filename, string ext, string text, NFOS.FileSystem.Structures str, char user_orders)
{
int condition = 0;
bool exist = false;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
exist = true;
ind = i;
break;
}
}
if (exist)
{
if (user_orders == 'a')
{
condition = 1;
}
else if (user_orders == 'g')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[1] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
else if (user_orders == 'o')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[4] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
}
if (condition == 0)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют производить записи в данный файл.");
}
else if (condition == 1)
{
/*Разбираем строку*/
char[] char_text = new char[text.Length];
text.CopyTo(0, char_text, 0, text.Length);
int record = 0;
int cluster_full = 0;
int prev_cluster_ind = str.root[ind].ft_cl;
int index = 0;
bool end = false;
BinaryReader br = new BinaryReader(System.IO.File.Open(PATH, FileMode.Open));
while (!end)
{
br.BaseStream.Seek((((FILES_FIRST_CLUSTER - 2) + prev_cluster_ind) * CLUSTER_SIZE) + cluster_full, SeekOrigin.Begin);
if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] != 999))
{
prev_cluster_ind = str.fat_table[prev_cluster_ind - 1];
cluster_full = 0;
}
else if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] == 999))
{
end = true;
}
if (br.ReadChar() == '\0')
{
break;
}
//text += Convert.ToString(br.ReadChar());
record++;
cluster_full++;
}
br.Close();
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
record = 0;
while (record != char_text.Length)
{
bw.BaseStream.Seek((((FILES_FIRST_CLUSTER - 2) + prev_cluster_ind) * CLUSTER_SIZE) + cluster_full, SeekOrigin.Begin);
/*Если кластер заполнен*/
if (cluster_full == CLUSTER_SIZE)
{
/*Поиск пустого кластера*/
for (int i = 0; i < CLUSTERS_COUNT; i++)
{
if (str.fat_table[i] == 0)
{
str.fat_table[prev_cluster_ind - 1] = Convert.ToUInt16(i + 1);
str.fat_table[i] = 999;
prev_cluster_ind = i + 1;
cluster_full = 0;
break;
}
}
/*Если места нет*/
if (cluster_full != 0)
{
Console.WriteLine("Не хватает места на логическом диске. Введенная информация будет урезана.");
record++;
break;
}
}
bw.Write(char_text[index]);
cluster_full++;
index++;
record++;
}
bw.Close();
str.root[ind].last_data = DateTime.Now.ToString();
str.root[ind].size = record + str.root[ind].size;
str.fat_cp_table = str.fat_table;
str.SaveFAT();
str.SaveCopyFAT();
str.SaveRoot();
}
}
/// <summary>
/// Удаление файла
/// </summary>
/// <param name="filename"></param>
/// <param name="ext"></param>
/// <param name="str"></param>
/// <param name="user_orders"></param>
public void RemoveFile(string filename, string ext, NFOS.FileSystem.Structures str, char user_orders)
{
int condition = 0;
bool exist = false;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
exist = true;
ind = i;
break;
}
}
if (exist)
{
if (user_orders == 'a')
{
condition = 1;
}
else if (user_orders == 'g')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[1] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
else if (user_orders == 'o')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[4] == 'w')
{
condition = 1;
}
else
{
condition = -1;
}
}
}
if (condition == 0)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют удалить данный файл.");
}
else if (condition == 1)
{
/*Зачищаем кластеры*/
if (str.fat_table[str.root[ind].ft_cl - 1] != 999)
{
int i = str.root[ind].ft_cl - 1;
int s_ind = str.root[ind].ft_cl - 1;
BinaryWriter bw = new BinaryWriter(System.IO.File.OpenWrite(PATH));
while (str.fat_table[i] != 999)
{
bw.BaseStream.Seek((((FILES_FIRST_CLUSTER - 1) + i) * CLUSTER_SIZE), SeekOrigin.Begin);
for (int k = 0; k < CLUSTERS_COUNT; k++)
{
bw.Write(Convert.ToByte(0));
}
int j = str.fat_table[i] - 1;
str.fat_table[i] = 0;
i = j;
}
str.fat_table[i] = 0;
bw.BaseStream.Seek((((FILES_FIRST_CLUSTER - 1) + i) * CLUSTER_SIZE), SeekOrigin.Begin);
for (int k = 0; k < CLUSTERS_COUNT; k++)
{
bw.Write(Convert.ToByte(0));
}
bw.Close();
}
str.root[ind].file_name = null;
str.root[ind].ext = null;
str.root[ind].last_data = null;
str.root[ind].ft_cl = 0;
str.root[ind].size = 0;
str.root[ind].file_orders = null;
str.fat_table[ind] = 0;
str.fat_cp_table = str.fat_table;
str.SaveFAT();
str.SaveCopyFAT();
BinaryWriter bw1 = new BinaryWriter(System.IO.File.OpenWrite(PATH));
bw1.BaseStream.Seek(((ROOT_FIRST_CLUSTER - 1) * CLUSTER_SIZE), SeekOrigin.Begin);
byte b = 0;
for (int i = 0; i < ROOT_LENGTH; i++)
{
bw1.Write(b);
}
bw1.Close();
str.SaveRoot();
Array.Resize(ref str.root, 0);
str.LoadRoot();
}
}
/// <summary>
/// Копирование файла
/// </summary>
/// <param name="filename"></param>
/// <param name="ext"></param>
/// <param name="copy_filename"></param>
/// <param name="copy_ext"></param>
/// <param name="str"></param>
/// <param name="user_orders"></param>
public void CopyFile(string filename, string ext, string copy_filename, NFOS.FileSystem.Structures str, char user_orders)
{
int condition = 0;
bool exist = false;
bool copy_exist = false;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
exist = true;
ind = i;
}
else if ((copy_filename == str.root[i].file_name) && (ext == str.root[i].ext))
{
copy_exist = true;
}
}
if ((exist) && (!copy_exist))
{
if (user_orders == 'a')
{
condition = 1;
}
else if (user_orders == 'g')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[1] == 'w')
{
condition = 1;
}
else
{
condition = -2;
}
}
else if (user_orders == 'o')
{
char[] file_orders = new char[FILE_ORDERS_LENGTH];
str.root[ind].file_orders.CopyTo(0, file_orders, 0, str.root[ind].file_orders.Length);
if (file_orders[4] == 'w')
{
condition = 1;
}
else
{
condition = -2;
}
}
}
else if (!exist)
{
condition = -1;
}
else if (copy_exist)
{
condition = 0;
}
if (condition == -1)
{
Console.WriteLine("Файл не найден.");
}
else if (condition == 0)
{
Console.WriteLine("Файл с таким именем уже существует.");
}
else if (condition == -2)
{
Console.WriteLine("Нет доступа ");
}
else if (condition == 1)
{
/*Читаем содержание файла*/
int record = 0;
int cluster_full = 0;
int prev_cluster_ind = str.root[ind].ft_cl;
string text = "";
bool end = false;
BinaryReader br = new BinaryReader(System.IO.File.Open(PATH, FileMode.Open));
while (!end)
{
br.BaseStream.Seek((((FILES_FIRST_CLUSTER - 2) + prev_cluster_ind) * CLUSTER_SIZE) + cluster_full, SeekOrigin.Begin);
if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] != 999))
{
prev_cluster_ind = str.fat_table[prev_cluster_ind - 1];
cluster_full = 0;
}
else if ((cluster_full == CLUSTER_SIZE) && (str.fat_table[prev_cluster_ind - 1] == 999))
{
end = true;
}
text += Convert.ToString(br.ReadChar());
record++;
cluster_full++;
}
br.Close();
/*Создаем новый файл с считанным текстом*/
CreateFile(copy_filename, ext, str, user_orders);
OpenTruncate(copy_filename, ext, text, str, user_orders);
}
}
#endregion
#region Системные вызовы для работы с пользователями
/// <summary>
/// Создание нового пользователя
/// </summary>
/// <param name="name"></param>
/// <param name="gid"></param>
/// <param name="password"></param>
/// <param name="orders"></param>
/// <param name="uid"></param>
/// <param name="str"></param>
public void CreateUser(string name, ushort gid, string password, char orders, char cur_orders, NFOS.FileSystem.Structures str)
{
int condition = 10;
int usr_ct = 0;
for (int i = 0; i < str.sb.max_usr_ct; i++)
{
/*Проверка на существование такого ника*/
if (name == str.usr_table[i].name)
{
condition = 0;
}
/*Подсчет существующих пользователей*/
if (str.usr_table[i].name != null)
{
usr_ct++;
}
}
/*Проверка на забитость учетных записей и на права*/
if (usr_ct == str.sb.max_usr_ct)
{
condition = -1;
}
else if (cur_orders != 'a')
{
condition = -2;
}
else if (condition != 0)
{
condition = 1;
}
/*Выполнение системного вызова*/
if (condition == -2)
{
Console.WriteLine("Ваши права не позволяют использовать данную команду.");
}
else if (condition == -1)
{
Console.WriteLine("В данный момент создано максимальное количество учетных записей.");
}
else if (condition == 0)
{
Console.WriteLine("Учетная запись с таким именем уже существует.");
}
else if (condition == 1)
{
/*Обновление таблицы пользователей*/
for (ushort i = 0; i < str.sb.max_usr_ct; i++)
{
if (str.usr_table[i].name == null)
{
str.usr_table[i].uid = Convert.ToUInt16(i+1);
str.usr_table[i].name = name;
if (gid == 1)
{
str.usr_table[i].gid = Convert.ToUInt16(1);
str.usr_table[i].group_name = "admin";
}
else if(gid == 2)
{
str.usr_table[i].gid = Convert.ToUInt16(2);
str.usr_table[i].group_name = "moder";
}
else if (gid == 3)
{
str.usr_table[i].gid = Convert.ToUInt16(3);
str.usr_table[i].group_name = "user";
}
/*Хеширование пароля*/
MD5 md5Hasher = MD5.Create();
StringBuilder sBuilder = new StringBuilder();
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(password));
for (int j = 0; j < data.Length; j++)
{
sBuilder.Append(data[j].ToString("x2"));
}
password = sBuilder.ToString();
str.usr_table[i].password_hash = password;
str.usr_table[i].orders = orders;
break;
}
}
str.SaveUserTable();
}
}
/// <summary>
/// Демонстрация всех учетных записей
/// </summary>
/// <param name="str"></param>
public void ShowUsers(NFOS.FileSystem.Structures str)
{
Console.WriteLine();
for (int i = 0; i < MAX_USERS_COUNT; i++)
{
if (str.usr_table[i].name != null)
{
Console.WriteLine(str.usr_table[i].uid + " " + str.usr_table[i].name + " " + str.usr_table[i].group_name + " " + str.usr_table[i].orders);
}
}
Console.WriteLine();
}
/// <summary>
/// Удаление пользователя
/// </summary>
/// <param name="uid"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void RemoveUser(ushort uid, NFOS.FileSystem.Structures str, char orders)
{
if (orders == 'a')
{
if (uid != 1)
{
for (int i = 0; i < MAX_USERS_COUNT; i++)
{
if (uid == str.usr_table[i].uid)
{
str.usr_table[i].uid = 0;
str.usr_table[i].name = null;
str.usr_table[i].gid = 0;
str.usr_table[i].group_name = null;
str.usr_table[i].password_hash = null;
str.usr_table[i].orders = ' ';
}
}
}
else
{
Console.WriteLine("Невозможно удалить администратора.");
}
}
else
{
Console.WriteLine("Ваши права не позволяют выполнять данную операцию.");
}
}
#endregion
#region Системные вызовы для изменения прав
/// <summary>
/// Изменение прав доступа к файлу для группы
/// </summary>
/// <param name="file_name"></param>
/// <param name="ext"></param>
/// <param name="file_orders"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void ChModGroup(string file_name, string ext, string file_orders, NFOS.FileSystem.Structures str, char orders)
{
string cur_file_orders = "";
int condition = 0;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((file_name == str.root[i].file_name) && (ext == str.root[i].ext))
{
cur_file_orders = str.root[i].file_orders;
ind = i;
break;
}
}
if (cur_file_orders == "")
{
condition = 0;
}
else if (orders != 'a')
{
condition = -1;
}
else
{
condition = 1;
}
if (condition == 0)
{
Console.WriteLine("Данный файл не существует.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют изменить права доступа к файлу.");
}
else if (condition == 1)
{
char[] char_orders = new char[FILE_ORDERS_LENGTH];
cur_file_orders.CopyTo(0, char_orders, 0, cur_file_orders.Length);
char[] take_orders = new char[FILE_ORDERS_LENGTH];
file_orders.CopyTo(0, take_orders, 0, file_orders.Length);
if (((take_orders[0] == 'r') || (take_orders[0] == '-')) && ((take_orders[1] == 'w') || (take_orders[1] == '-')) && ((take_orders[2] == 'x') || (take_orders[2] == '-')))
{
char_orders[0] = take_orders[0];
char_orders[1] = take_orders[1];
char_orders[2] = take_orders[2];
}
else
{
Console.WriteLine("Права не правильно заданы.");
}
str.root[ind].file_orders = "";
for (int i = 0; i < FILE_ORDERS_LENGTH; i++)
{
str.root[ind].file_orders += char_orders[i];
}
str.SaveRoot();
}
}
/// <summary>
/// Изменение прав доступа к файлу для других
/// </summary>
/// <param name="file_name"></param>
/// <param name="ext"></param>
/// <param name="file_orders"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void ChModOther(string file_name, string ext, string file_orders, NFOS.FileSystem.Structures str, char orders)
{
string cur_file_orders = "";
int condition = 0;
int ind = 0;
for (int i = 0; i < str.root.Length; i++)
{
if ((file_name == str.root[i].file_name) && (ext == str.root[i].ext))
{
cur_file_orders = str.root[i].file_orders;
ind = i;
break;
}
}
if (cur_file_orders == "")
{
condition = 0;
}
else if ((orders != 'a') && (orders != 'g'))
{
condition = -1;
}
else
{
condition = 1;
}
if (condition == 0)
{
Console.WriteLine("Данный файл не существует.");
}
else if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют изменить права доступа к файлу.");
}
else if (condition == 1)
{
char[] char_orders = new char[FILE_ORDERS_LENGTH];
cur_file_orders.CopyTo(0, char_orders, 0, cur_file_orders.Length);
char[] take_orders = new char[FILE_ORDERS_LENGTH];
file_orders.CopyTo(0, take_orders, 0, file_orders.Length);
if (((take_orders[0] == 'r') || (take_orders[0] == '-')) && ((take_orders[1] == 'w') || (take_orders[1] == '-')) && ((take_orders[2] == 'x') || (take_orders[2] == '-')))
{
char_orders[3] = take_orders[0];
char_orders[4] = take_orders[1];
char_orders[5] = take_orders[2];
}
else
{
Console.WriteLine("Права не правильно заданы.");
}
str.root[ind].file_orders = "";
for (int i = 0; i < FILE_ORDERS_LENGTH; i++)
{
str.root[ind].file_orders += char_orders[i];
}
str.SaveRoot();
}
}
/// <summary>
/// Изменение прав пользователя
/// </summary>
/// <param name="uid"></param>
/// <param name="take_orders"></param>
/// <param name="str"></param>
/// <param name="orders"></param>
public void ChOrders(ushort uid, char take_orders, NFOS.FileSystem.Structures str, char orders)
{
int condition = 0;
int ind = 0;
for (int i = 0; i < MAX_USERS_COUNT; i++)
{
if (str.usr_table[i].uid == uid)
{
condition = 1;
ind = i;
}
}
if (orders != 'a')
{
condition = -1;
}
if (condition == -1)
{
Console.WriteLine("Ваши права не позволяют изменять права других пользователей.");
}
else if (condition == 0)
{
Console.WriteLine("Заданный пользователь не найден.");
}
else if (condition == 1)
{
if (uid == 1)
{
Console.WriteLine("Нельзя поменять права администратора.");
}
else
{
str.usr_table[ind].orders = take_orders;
}
str.SaveUserTable();
}
}
#endregion
}
}
Processes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace NFOS.Processes
{
class Processes
{
/*Размер разделяемой памяти*/
const int BUFFER_SIZE = 256;
/*Размер одной страницы разделяемой памяти*/
const int PAGE_SIZE = 32;
/*Количество страниц в разделяемой памяти*/
const int QUANTITY_PAGE = BUFFER_SIZE / PAGE_SIZE;
/*Строка синформацией, которая будет передаватся через разделяемую память*/
const string CONTENT = "Transmitted message";
/*Массив из байт, который имитирует разделяемую память*/
byte[] buffer;
/*Массив семафоров*/
bool[] semafor;
int save_page;
public Processes()
{
buffer = new byte[BUFFER_SIZE];
semafor = new bool[QUANTITY_PAGE];
}
/// <summary>
/// Установка состояния указанной страницы в значение занято
/// </summary>
/// <param name="page">Страница, состояние которой необходимо изменить</param>
private void SetPageBusy(int page)
{
semafor[page] = true;
}
/// <summary>
/// Установка состояния указанной страницы в значение свободно
/// </summary>
/// <param name="page">Страница, состояние которой необходимо изменить</param>
private void SetPageFree(int page)
{
semafor[page] = false;
}
/// <summary>
/// Получить состояние указанной страницы
/// </summary>
/// <param name="page">Страница, состояние которой необходимо узнать</param>
private bool GetStatusPage(int page)
{
return semafor[page];
}
/// <summary>
/// Запуск имитации межпроцессного взаимодействия двух процессов
/// </summary>
public void Start()
{
Thread proc_1 = new Thread(FirstProc);
proc_1.Start();
Thread.Sleep(850);
Thread proc_2 = new Thread(SecondProc);
proc_2.Start();
while (proc_1.ThreadState != ThreadState.Stopped || proc_2.ThreadState != ThreadState.Stopped)
Thread.Sleep(100);
}
/// <summary>
/// Получение номера первой свободной странице в разделяемой памяти
/// </summary>
/// <returns></returns>
private int GetFirstEmptyPage()
{
int res = 0;
Console.WriteLine("Процесс 1 ищет свободную страницу.");
for (int i = 0; i < QUANTITY_PAGE; i++)
{
if (buffer[i * PAGE_SIZE] == '\0')
{
res = i;
break;
}
}
Thread.Sleep(500);
save_page = res;
Console.WriteLine("Процесс 1 нашел пустую страницу " + (res + 1) + ".");
return res;
}
private void ClearPage(int page)
{
Console.WriteLine("Процесс 2 очищает страницу " + (page + 1) + ".");
Thread.Sleep(300);
for (int i = 0; i < PAGE_SIZE; i++)
{
buffer[(PAGE_SIZE * page) + i] = Convert.ToByte(0);
}
Console.WriteLine("Страница " + (page + 1) + " была очищена.");
}
/// <summary>
/// Имитация передачи процессом 1 информации в разделяемую память
/// </summary>
private void FirstProc()
{
int record_page = GetFirstEmptyPage();
if (GetStatusPage(record_page) != true)
{
SetPageBusy(record_page);
Console.WriteLine("Процесс 1 занял страницу " + (record_page + 1) + ".");
Console.WriteLine("Процесс 1 начинает записывать информацию: " + CONTENT);
for (int i = 0; i < CONTENT.Length; i++)
{
buffer[i * (record_page + 1)] = (byte)CONTENT[i];
Console.WriteLine("Процесс 1 записывает информацию в страницу " + (record_page + 1) + ".");
Thread.Sleep(1400);
}
SetPageFree(record_page);
Console.WriteLine("Процесс 1 записал информацию и освободил страницу " + (record_page + 1) + ".");
}
}
/// <summary>
/// Имитация считывания процессом 2 информации из разделяемой памяти
/// </summary>
private void SecondProc()
{
while (GetStatusPage(save_page) == true)
{
Console.WriteLine("Процесс 2 пытается получить доступ к странице " + (save_page + 1) + ".");
Thread.Sleep(1400);
}
if (GetStatusPage(save_page) != true)
{
SetPageBusy(save_page);
Console.WriteLine("Процесс 2 занял страницу " + (save_page + 1) + "!");
Console.Write("Процесс 2 считывает информацию из страницы " + (save_page + 1) + ": ");
for (int i = 0; i < PAGE_SIZE; i++)
if (buffer[i * (save_page + 1)] != '\0')
Console.Write((char)buffer[i * (save_page + 1)]);
Console.WriteLine();
ClearPage(save_page);
SetPageFree(save_page);
Console.WriteLine("Процесс 2 освободил страницу " + (save_page + 1) + ".");
}
}
}
}
Приложение В
Руководство пользователя
В.1 Условия выполнения программы
Системные требования: компьютер под управлением операционной системы MS Windows 9x/2000/XP/Vista/7, монитор, клавиатура. Программа запускается спомощью файла NFOS.exe
В.2 Выполнение программы
Если запуск программы производится первый раз, то появится сообщение о том, что следует создать логический диск. Если вам это не требуется, то следует ввести “exit”, иначе “format”. После этого логический диск будет создан и программа попросит ввести логин и пароль. После форматирования поумолчанию создается администратор с логином “admin” и паролем “admin”. Если ввести в поле логина “exit”, то программа закроется.
Если логин и пароль введены правильно, то произойдет переход в консоль команд. Сдесь могут производится различные операции с файлами и пользователями, перечень которых был описан выше.
Для выхода из консоли команд, следует ввести “exit”.
Размещено на Allbest.ru
Подобные документы
Общая организация файловой системы. Виртуальные страницы. Команды для работы с ФС. Способы организации файлов. Системные вызовы управления процессами. Алгоритм работы планировщика процессов. Мультипрограммный режим работы ОС. Структура ядра системы.
курсовая работа [645,3 K], добавлен 23.03.2015Определение файловой системы. Виртуальные и сетевые файловые системы. Структура и версии системы FAT. Определение максимального размера кластера. Драйверы файловой системы, файлы и каталоги. Способы доступа к файлам, находящимся на удаленном компьютере.
доклад [29,2 K], добавлен 11.12.2010Изучение операционной системы Linux: элементов файлов, структуры каталогов и прав доступа к ним. Получение практических навыков по работе с некоторыми командами данной ОС. Теоретические сведения и практические навыки по работе с процессами Linux.
лабораторная работа [847,5 K], добавлен 16.06.2011Изучение основных аспектов моделирования операционной системы. Исследование принципов организации псевдопараллельной работы процессов. Анализ алгоритмов диспетчеризации процессов. Проектирование подсистемы управления памятью и запоминающими устройствами.
курсовая работа [1,7 M], добавлен 12.01.2014Роль многопрограммной обработки информации для развития операционной системы. Загрузка операционной системы и основных файлов Windows. Базовая система ввода-вывода. Внутренние и внешние команды DOS. Спецификация учебных элементов. Граф учебной информации.
контрольная работа [25,0 K], добавлен 24.10.2010Работа с объектами операционной системы Windows: основные понятия и горячие клавиши. Создание и редактирование файлов и папок. Скриншоты и графический редактор Paint. Редактирование простейших текстовых документов в Блокноте. Работа с калькулятором.
лабораторная работа [16,6 K], добавлен 30.11.2010Методы и приемы работы в операционной системе Windows XP, часто используемой при работе с персональным компьютером. Средства по настройке и конфигурации операционной системы. Соответствие используемых аппаратных средств потребностям пользователя.
курсовая работа [4,7 M], добавлен 15.07.2009Правовые основы защиты информации на предприятии. Анализ среды пользователей. Автоматизированная система предприятия. Краткие сведения об операционной системе Windows XP. Классификация троянских программ. Способы защиты операционной системы Windows XP.
дипломная работа [187,3 K], добавлен 14.07.2013Что такое операционная система, ее главные функции и классификация. Характеристика операционной системы MS-DOS4, организация данных. Особенности основных операций и команд системы, отработка практических навыков использования команд для работы на ПК.
контрольная работа [13,0 K], добавлен 04.03.2011Основные защитные механизмы операционной системы семейства Unix, недостатки ее защитных механизмов. Идентификаторы пользователя и группы пользователей. Защита файлов, контроль доступа, уязвимость паролей. Проектирование символов для матричных принтеров.
курсовая работа [488,8 K], добавлен 22.06.2011
