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

C program to detect USB drive in Linux

我有一个嵌入式设备 运行 Linux 埃。我需要检测 USB 驱动器。所以当插入U盘时,我需要自动将数据从U盘复制到嵌入式设备的内存中。

为了检测 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 埃。所以只有通用的 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;
}