正确自动卸载笔式驱动器

Correct auto unmount of pen drive

我搜索过类似的帖子,但没有找到。我正在寻找一些建议或正确方向的观点,因为我找不到关于这个主题的太多信息。

我正在尝试在来自 buildroot 的 raspberry pi 4 运行ning 自定义 linux 构建上编写守护进程。守护进程使用 udev (libudev.h) 和 epoll (sys/epoll.h),检测新插入的笔式驱动器,创建目录并安装设备。它还检测到所述设备的删除,卸载然后删除目录。

它在移除笔式驱动器之前运行良好,尽管正在执行卸载(没有任何错误 return),但当我重新插入笔式驱动器“FAT-fs”时,我总是收到此消息(sda1) 卷未正确卸载。某些数据可能已损坏。请 运行 fsck”。 我究竟做错了什么?我怎样才能正确卸载它?

 //pen removed
 if(!action.compare("remove") && !partition.compare("partition")){
    //if directory exists
    dir = opendir(path.c_str());
    if(dir){
       //close directory to be able to unmount
       close(dir);
       //unmount
       status = umount(path.c_str());
       if(status != 0)
           syslog(LOG_ERR, "%m\n");
       //remove the directory
       status = rmdir(path.c_str());
       if(status != 0)
           syslog(LOG_ERR, "%m\n");
       }
}
//pen inserted
else if(!action.compare("add") && !partition.compare("partition")){
    //if directory doesn't exist
    dir = opendir(path.c_str());
    if(!dir){
        //create the directory 
        status = mkdir(path.c_str(), 777); 
        if(status != 0)
           syslog(LOG_ERR, "%m\n");
        }
        //mount 
        status = mount(devicenode.c_str(), path.c_str(), "vfat", MS_NOATIME, NULL);
        if(status != 0)
           syslog(LOG_ERR, "%m\n");
        }
}

必须先卸载驱动器,然后 移除笔式驱动器。这显然不可能自动完成。

一个选项是使用 -o sync 挂载选项进行挂载;这将确保立即刷新文件,从而减少文件系统损坏的可能性。但是,据我所知,它不会删除警告消息。

警告消息是由于在安装时在笔式驱动器上设置了脏位,并在卸载时将其清除。当它被安装并且已经设置了脏位时,打印警告。

Windows 通过在完成对笔式驱动器的写入后清除脏位并在开始新的写入时再次设置它来解决此问题。据我所知,Linux 没有类似的功能。你可以尝试在内核中实现它。