Mark
Mark

Reputation: 23

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?

Upvotes: 2

Views: 2721

Answers (2)

amso
amso

Reputation: 514

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.

Upvotes: 2

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

You probably want to use udev rules.

Running external programs upon certain events

Yet another reason for writing udev rules is to run a particular program when a device is connected or disconnected. For example, you might want to execute a script to automatically download all of your photos from your digital camera when it is connected.

Upvotes: 1

Related Questions