1
votes

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

1
Do you get udev? If so, you could do something with a udev rule.Joe
A possible workaround could be unmount the USB programmatically after the copy transfer was performed because maybe the physical unplug of the USB is not detected properly.JTejedor
@JTejedor I did unmount it properly using umount /media/sda1 but sometimes it still remains there. Thats why I am looking for another approach.S Andrew
@Joe udev command is not available.!S Andrew
You could check that a usb drive is connected by parsing the result of mount | grep sda command.Mathieu

1 Answers

1
votes

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