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