C程序检测Linux中的USB驱动器
问题描述:
我有一个运行Linux Angstrom的嵌入式设备。我需要检测一个USB驱动器。所以当插入USB驱动器时,我需要自动将数据从USB复制到嵌入式设备的内部存储器。C程序检测Linux中的USB驱动器
检测USB,我使用下面的代码:
DIR* dir = opendir("/media/sda1/");
if (dir)
{
printf("USB detected\n");
//rest of the code
//to copy data from the USB
}
这工作正常,但复制完成后,有时,我删除了USB,但安装点(SDA1)的名称仍然存在。因此,在删除USB之后,它会再次尝试复制数据(因为sda1存在于介质中),然后显示错误,因为物理上没有USB连接。如何检测USB是否连接,以及如果连接,然后在复制后如何正确弹出,最佳方法是什么?在这里,我不能使用udisks
,因为它不适用于我用于此嵌入式设备的linux angstrom。所以只有通用的linux命令才能工作。
任何帮助。由于
答
一个幼稚的做法是:
- 执行
mount | grep /dev/sda1
- 解析输出:如果没有输出,这意味着
sda1
未安装
您可能需要使代码适应您的特定平台。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* launch a command and gets its output */
FILE *f = popen("mount | grep /dev/sda1", "r");
if (NULL != f)
{
/* test if something has been outputed by
the command */
if (EOF == fgetc(f))
{
puts("/dev/sda1 is NOT mounted");
}
else
{
puts("/dev/sda1 is mounted");
}
/* close the command file */
pclose(f);
}
return 0;
}
你得到udev吗?如果是这样,你可以用udev规则来做一些事情。 – Joe
可能的解决方法可能是在执行复制传输后以编程方式卸载USB,因为可能未正确检测到USB的物理拔出。 – JTejedor
@JTejedor我用'umount/media/sda1'正确卸载了它,但有时它仍然存在。这就是为什么我正在寻找另一种方法。 –