操作系统原理 2026

读取字符串与写入密码

原片 01:02:00—01:03:25

Everything is a File,这个发射器也是 file。从里面读,总会得到 this is dangerous 字符串。既然能返回它,理论上也能返回其他数据,比如从发射井传感器读到的数据。

图 55:launcher_read 返回字符串(01:02:19)。
图 55:launcher_read 返回字符串(01:02:19)。

launcher_read 的函数体片段;offset、count 和 buf 为调用参数。

if (*offset != 0) {
    return 0;
} else {
    const char *data = "This is dangerous!\n";
    size_t datalen = strlen(data);
    if (count > datalen) {
        count = datalen;
    }
    if (copy_to_user(buf, data, count)) {
        return -EFAULT;
    }
    *offset += count;
    return count;
}

这里仅把字符串拷贝到用户态。write 时则验证密码,不能像 LED 那样,写一个 1 就发射。程序写入密码,驱动负责校验。实际系统除了软件校验,还可能要插入两把钥匙,同时转动,并有冗余逻辑,避免误操作。

图 56:launcher_write 复制并比较输入(01:02:52)。
图 56:launcher_write 复制并比较输入(01:02:52)。

launcher_write 中复制用户输入的片段,后续比较密码并输出字符图案的分支见原画面。

char databuf[4] = "\0\0\0\0";
if (count > 4) {
    count = 4;
}
if (copy_from_user(databuf, buf, count)) {
    return -EFAULT;
}
// 后续:memcmp(databuf, "\x01\x14\x05\x14", 4)

比如部件误短路、误短接时,也要确保不会误发射,需要很多检查。这里仅做简单的 memory compare,收到正确 password 就执行模拟发射。以前写驱动挺麻烦,今天可以直接 vibe coding。旧代码无法在新 kernel 上编译。

输入关键词,搜索全部 30 节课。