简体   繁体   English

如何在 Linux 中的 C++ 中检测 SD 卡的存在

[英]How to detect SD card presence in C++ In Linux

Good afternoon,下午好,

I'm running a simple loop for checking whether SD card has been inserted or removed, but it doesn't seem to work correctly all the time.我正在运行一个简单的循环来检查 SD 卡是否已插入或移除,但它似乎并没有一直正常工作。

The problem is, when the program starts with SD card inserted, the if(f.good()) statement is True .问题是,当程序以插入的 SD 卡启动时, if(f.good())语句为True

When SD card is removed this statement is False .当取出 SD 卡时,此语句为False

However, when the SD card is re-inserted, this statement is still False .但是,当重新插入 SD 卡时,该语句仍然为False

Is there a more reliable way in C++ to detect SD card presence? C++ 中是否有更可靠的方法来检测 SD 卡的存在? I'm Running Linux Yocto, based on OpenEmbedded.我正在运行基于 OpenEmbedded 的 Linux Yocto。 I would prefer to avoid using any external libraries, and use file IO or system calls if possible.我宁愿避免使用任何外部库,并尽可能使用文件 IO 或系统调用。

Thanks.谢谢。

My loop is shown below,我的循环如下所示,

    while (running)
    {
        ifstream f("/dev/mmcblk1");
        if (f.good()) {
            f.close();
            if (!mounted)
            {
                system("mount /dev/mmcblk1p1 /mnt/Storage");   
                mounted = true;
            }
            sdPresent = true;
        }
        else {
            f.close();
            sdPresent = false;
            mounted = false;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

The proper direct way to know if a removable device has a media inserted is reading the device size from sysfs .了解可移动设备是否插入了媒体的正确直接方法是从sysfs读取设备大小。

In your case it would be somewhere like /sys/block/mmcblk1/size .在您的情况下,它将类似于/sys/block/mmcblk1/size That file should exist always, and contain a unsigned long long value.该文件应始终存在,并包含一个unsigned long long值。 If it is 0 then no media, if it is >0 then you have a media of that size.如果它是0则没有媒体,如果它>0那么你有一个该大小的媒体。

bool has_media()
{
    std::ifstream fsize("/sys/block/mmcblk1/size");
    unsigned long long size;
    return (fsize >> size) && (size > 0);
}

If, instead of polling and sleeping, you want proper notifications of the media insertion/removal, and you don't want / cannot use libudev, then you would need to use uevent and a netlink socket.如果,而不是轮询和睡眠,您想要媒体插入/删除的正确通知,并且您不想/不能使用 libudev,那么您将需要使用 uevent 和 netlink 套接字。 See this excelent answer with the details.请参阅此优秀答案的详细信息。

如果 SD 卡是唯一的 FAT32 分区,您可以简单地执行以下操作:

fdisk -l | grep FAT32 | cut -c 1-8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM