x01.os.13: 文件系统

            停了两天电,忽然得空闲。找来破吉他,已然不成弦。

          丁丁当当敲,敲到电来到。为把时间捡,熬夜三四点。

从我的置顶随笔 x01.Lab.Download 中下载 x01.os.12.tar.gz, 解压后由终端进入 os 目录,输入 bochs  命令即可见到如下界面:

  

注意下面的四行,分别是 open,write, read, unlink 文件。调用代码如下:

 1 void TestA() {
 2     int fd, n;
 3     char path[] = "/test";
 4     char bufw[] = "hello";
 5     const int Len = 3;
 6     char bufr[Len];
 7 
 8     fd = open(path , O_CREAT | O_RDWR);
 9     Print("fd: %d
", fd);
10 
11     n = write(fd, bufw, StrLength(bufw));
12     Print("write ok!
");
13 
14     close(fd);
15 
16     fd = open(path, O_RDWR);
17     n = read(fd, bufr, Len);
18     bufr[n] = 0;
19     Print("read: %s
", bufr);
20 
21     close(fd);
22 
23     if (unlink(path) == 0)
24         Print("unlink file: %s", path);
25 
26 //    Spin("TestA");
27     while (1) {
28             MilliDelay(2000);
29         }
30 }
TestA

按 F2 后,可切换到 tty2, 分别输入 hello 回车,this is a test 回车,可看到如下界面:

    

其调用代码如下:

 1 void TestB() {
 2     char ttyName[] = "/dev_tty1";
 3     int stdin = open(ttyName, O_RDWR);
 4     Assert(stdin == 0);
 5     int stdout = open(ttyName, O_RDWR);
 6     Assert(stdout == 1);
 7     char buf[128];
 8 
 9     while (1) {
10         write(stdout, "$ ", 2);
11 //        Spin("write");
12         int r = read(stdin, buf, 70);
13         buf[r] = 0;
14         if ( StrCompare(buf, "hello") == 0 ) {
15             write(stdout, "hello world!
",  13);
16         } else {
17             if (buf[0]) {
18                 write(stdout, "{", 1);
19                 write(stdout, buf, r);
20                 write(stdout, "}
", 2);
21             }
22         }
23     }
24 
25     Assert(0);
26     while (1) {
27             MilliDelay(2000);
28         }
29 }
TestB

两向对照,不难看出,文件的打开,读写,删除等功能已经具备,而 tty 也成功纳入了文件系统。

文件系统,本身并不复杂,不过超级块和索引节点两个结构。但文件系统的实现,却颇为繁难,不仅涉及到硬盘的操作,而且也涉及到 tty,进程间通信等诸多方面。在某种意义上讲,文件系统处于整个操作系统的核心。因为用户程序本身,也不过是个文件而已。搞清文件系统,一是看书,二是看代码,别无他途。

耗时多日,终于将文件系统运行成功,是为记。

原文地址:https://www.cnblogs.com/china_x01/p/4068910.html