feat: stdin/stdout into process
[lunaix-os.git] / lunaix-os / kernel / demos / iotest.c
1 #include <lunaix/fctrl.h>
2 #include <lunaix/foptions.h>
3 #include <lunaix/lunistd.h>
4 #include <lunaix/proc.h>
5 #include <lunaix/syslog.h>
6
7 LOG_MODULE("IOTEST")
8
9 #define STDIN 1
10 #define STDOUT 0
11
12 void
13 _iotest_main()
14 {
15     char test_sequence[] = "Once upon a time, in a magical land of Equestria. "
16                            "There were two regal sisters who ruled together "
17                            "and created harmony for all the land.";
18
19     // sda 设备 - 硬盘
20     //  sda设备属于容积设备(Volumetric Device),
21     //  Lunaix会尽可能缓存任何对此设备的上层读写,并使用延迟写入策略。(FO_DIRECT可用于屏蔽该功能)
22     int fd = open("/dev/sda", 0);
23
24     if (fd < 0) {
25         kprintf(KERROR "fail to open (%d)\n", geterrno());
26         return;
27     }
28
29     // 移动指针至512字节,在大多数情况下,这是第二个逻辑扇区的起始处
30     lseek(fd, 512, FSEEK_SET);
31
32     // 总共写入 64 * 136 字节,会产生3个页作为缓存
33     for (size_t i = 0; i < 64; i++) {
34         write(fd, test_sequence, sizeof(test_sequence));
35     }
36
37     // 随机读写测试
38     lseek(fd, 4 * 4096, FSEEK_SET);
39     write(fd, test_sequence, sizeof(test_sequence));
40
41     char read_out[256];
42     write(STDOUT, "input: ", 8);
43     int size = read(STDIN, read_out, 256);
44
45     write(STDOUT, "your input: ", 13);
46     write(STDOUT, read_out, size);
47     write(fd, read_out, size);
48     write(STDOUT, "\n", 1);
49
50     // 读出我们写的内容
51     lseek(fd, 512, FSEEK_SET);
52     read(fd, read_out, sizeof(read_out));
53
54     // 将读出的内容直接写入tty设备
55     write(STDOUT, read_out, sizeof(read_out));
56     write(STDOUT, "\n", 1);
57
58     // 关闭文件,这同时会将页缓存中的数据下发到底层驱动
59     close(fd);
60
61     kprint_hex(read_out, sizeof(read_out));
62 }