用于检测Linux中USB驱动器的C程序

时间:2017-07-04 07:25:41

标签: c linux usb

我有一台运行Linux Angstrom的嵌入式设备。我需要检测USB驱动器。因此,当插入USB驱动器时,我需要自动将数据从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是否已连接的最佳方法,如果已连接,则在复制后如何正确弹出USB。在这里我不能使用udisks,因为它不适用于我用于此嵌入式设备的linux版本。所以只有通用的linux命令才有效。

任何帮助。感谢

1 个答案:

答案 0 :(得分:0)

一种天真的方法如下:

  • 执行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;
}