以编程方式检测 SD 卡写保护
回到软盘的美好时代,如果您启用软盘的写保护,DOS 会友好地告诉您不能写入它。现在我们的SD卡可以容纳数千张软盘的内容,而且我们仍然有写保护——有时它很方便。但没有人能告诉我我不能写入它,至少在 Linux 上是这样。我有一个可爱的脚本,可以按照我喜欢的方式对 SD 卡进行分区和格式化。我调试了1/2个小时才发现SD卡被写保护了。
那么问题来了,软件有没有办法检测到这种情况呢?
谢谢,
Back in the good-old days of floppy, if you enable write protection of a floppy, DOS would kindly tell you that you cannot write to it. Now we have SD card that can hold the content of thousands of floppy and we still have the write protection - and it's handy sometime. But nobody is able to tell me I can't write to it, at least on Linux. I have a lovely script that partition and format a SD card in a way I like. It took me 1/2 hour of debugging just to find out that the SD card is write-protected.
So the question, is there a way that the software can detect such condition?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
驱动程序知道卡何时被写保护,并且当您通过命令行安装它时它实际上会发出警告:
如果您想在设备级别自行检查,可以使用
hdparm
命令用于查询磁盘设备的只读状态,一般包括SD卡和U盘。该程序应该在大多数 GNU/Linux 发行版中可用,通常位于名为“hdparm”的包中。如果您不是 root,请务必指定
hdparm
命令的完整路径;当然,这假设您拥有卡的读取权限。例如:我的SD卡已插入,检测为
/dev/sdc
,并且写保护选项卡位于解锁:当我将写保护选项卡滑动到锁定时,重新插入卡,然后再次运行命令:
如果您想在 shell 脚本中执行此操作,您可以尝试以下操作:
注意:如果您更喜欢在 C 中执行此操作,您可以尝试:
errno
值EROFS
(只读文件系统),或者...ioctl ()
名为BLKROGET
< /a>,并检查是否结果值非零;这就是hdparm
的工作方式。The driver knows when the card is write-protected, and it actually warns when you mount it via command line:
In case you would like to check it yourself at device level, you can use the
hdparm
command to query read-only status of disk device, including SD card and USB flash drive in general. This program should be available in most GNU/Linux distributions, commonly in a package named "hdparm".If you are not root, be sure to specify full path to the
hdparm
command; and this assumes you have read permission on your card of course.For example: my SD card is inserted, detected as
/dev/sdc
, and write protection tab is at Unlock:When I slided the write protection tab to Lock, re-insert the card, and run the command again:
If you would like to do it in shell script, you can try something like:
Note: If you prefer to do it in C, you can try either:
errno
valueEROFS
(Read-only file system), or...ioctl()
namedBLKROGET
, and check if the result value is nonzero; this is the wayhdparm
work.