S Andrew
S Andrew

Reputation: 7298

C program to detect USB drive in Linux

I have a embedded device running Linux Angstrom. I need to detect a USB drive. So when a USB drive is inserted, I need to automatically copy data from the USB to internal memory of the embedded device.

To detect the USB, I am using below code:

DIR* dir = opendir("/media/sda1/");
if (dir)
{
   printf("USB detected\n");
   //rest of the code
   //to copy data from the USB
}

This works normally but sometimes after copying is done, I remove the USB but the name of the mount point (sda1) remains there. So after removing the USB, it again try to copy the data (because sda1 is there in media) and then shows error because physical no USB is connected. What is the best way to detect if USB is connected and if connected then after copying how to eject it properly. Here I cannot use udisks because its not available for the linux angstrom I am using for this embedded device. So only generic linux commands will work.

Any help. Thanks

Upvotes: 2

Views: 7900

Answers (1)

Mathieu
Mathieu

Reputation: 9689

One naive approach is the following:

  • execute mount | grep /dev/sda1
  • parse the output: if there is no output, that means that sda1 is not mounted

You may have to adapt the code to your specific platform.

#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;
}

Upvotes: 2

Related Questions