Search code examples
clinuxunixudev

How to detect or test on unix/linux dev node creation for usb flash drive insertion


I'm coding in C on a linux system. I want to insert a USB flash drive, let udev create the dev nodes (at /dev/sdc and /dev/sdc1, for example), and take an action only when /dev/sdc appears. What I've been doing is thinking of this as a wait loop in my C application, waiting for a dev node to be created by the udev daemon. Something like the following:

if( /* /dev/sdc exists */)
{
  do_something();
}
else
{
  wait();
}

My first problem is, what C library function can go in my if() test to return a value for "/dev/sdc exists." My second problem is, am I simply approaching this wrongly? Should I be using a udev monitor structure to detect this straight from udev?


Solution

  • You may want to take a look at fstat() from the standard library. This allows you to do a quick-and-dirty check on the presence/absence of the file and act upon that. basically you need to:

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    
    ....
    
    struct stat s;
    stat( "/pat/to/node" , &s );
    if ( IS_BLK(s.st_mode) ) {
        /* the file exists and is a block device */
    }
    

    This is not an elegant solution but answers your question. The code might need some tuning because I didn't try it but it should do the trick.

    Cheers.