gpt4 book ai didi

Linux下检测U盘的C程序

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:22 25 4
gpt4 key购买 nike

我有一个运行 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 是否已连接的最佳方法是什么,如果已连接,则复制后如何正确弹出。在这里我不能使用 udisks 因为它不适用于我用于此嵌入式设备的 linux angstrom。所以只有通用的 linux 命令可以工作。

任何帮助。谢谢

最佳答案

一种天真的方法如下:

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

关于Linux下检测U盘的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44899558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com