C Checking for a program accessing hardware

Is there a way to have my program check to see if another program is already accessing or attempting to access hardware, such as a webcam? A web search doesn't yield any results for this and I'm not even sure if FreeBSD has a way to check for this type of thing.
 
If I understand correctly, after reading through those, I would just have to run fstat on the specific device in /dev/ since FreeBSD generally treats devices as files? That would, at the very least, see when the last time the device was accessed. It would let me know if something is currently accessing the device but not specifically what program is accessing it? Thank you for the help. I really appreciate it.
 
Think about atomicity: You look with fstat or something like that. You find that nobody is accessing it right now. So you start. What if somebody else is doing exactly the same thing at the same time? This approach doesn't really work reliably.

The other question is this: Who is this other program that might be using the same hardware? Is it your own program, so you control both source code stacks? Is the device accessed as a /dev/xxx file? If yes, that opens some avenues. For example: If all the programs that use this hardware can be modified so they use exclusive locking (the O_EXLOCK flag when opening), then you can cause all other open attempts to fail or block. But since this type of locking is "advisory", it only works if all the programs that use the device use locking; even when the device is locked by your program, a normal program can just open() the device and do IO. If locking on the actual device file /dev/XX doesn't work, you could modify all your programs to use a sentinel file nearby; for example, when they want to use the device, they first create /tmp/dev_XX_is_open and lock it. AFAIK, you can not enable mandatory locking on the device file system, so that's out.

If the device is a serial port (of type /dev/ttyXX), then there is a well-known protocol involving lock files that nearly all programs that use serial ports will follow; in effect, this makes the advisory locking de-facto mandatory. But you said webcam, and that's probably not a serial port.

I don't know of a general solution that works against all programs, without using non-standard OS extensions that make locking mandatory. I don't know that FreeBSD has those, in particular not on the device file system.
 
Just a small correction:
Drivers access Hardware. Not userland programs.

A userland program can then communicate with the driver, eg. via the /dev files, sysctls, ...

You could read the man page of the relevant driver as a starting point (in your example a deamon webcamd)

Maybe look at this file:
/var/run/webcamd.*.0.pid
 
Back
Top