Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
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.

The problem is, when the program starts with SD card inserted, the if(f.good()) statement is True.

When SD card is removed this statement is False.

However, when the SD card is re-inserted, this statement is still False.

Is there a more reliable way in C++ to detect SD card presence? I'm Running Linux Yocto, based on OpenEmbedded. I would prefer to avoid using any external libraries, and use file IO or system calls if possible.

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));
    }
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The proper direct way to know if a removable device has a media inserted is reading the device size from sysfs.

In your case it would be somewhere like /sys/block/mmcblk1/size. That file should exist always, and contain a unsigned long long value. If it is 0 then no media, if it is >0 then you have a media of that size.

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. See this excelent answer with the details.

over 4 years ago · Santiago Trujillo Relatório

0

if the sd-card is the only FAT32 partition you can simply do:

fdisk -l | grep FAT32 | cut -c 1-8
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda