开发者

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

开发者 https://www.devze.com 2023-03-27 12:54 出处:网络
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\'v

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/s开发者_Python百科dc 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消