Julian Gold
Julian Gold

Reputation: 1286

Linux I2C file handles - safe to cache?

I am just starting to look at the I2C support on (embedded) linux (Beaglebone Black, to be precise). Since it's linux, everything is a file, so it's no surprise that I2C is too.

int file = open( "/dev/i2c-0", O_RDWR );

and then the actual address on that bus is selected through ioctl(). My question is this - is it safe, or even legal, to cache file for the duration of application execution? It would seem to my naive eyes that the overheading of opening a resource to read every 250ms would be an unnecessary strain on the kernel. So it is valid to open, and then just use ioctl() to switch address whenever I need to, or must I close() the descriptor between reads and writes?

Upvotes: 2

Views: 666

Answers (1)

sawdust
sawdust

Reputation: 17077

is it safe, or even legal, to cache file for the duration of application execution?

The file descriptor (that is returned from open()) is valid for as long as your program needs to keep executing.

Device nodes in /dev may resemble filenames, but they are treated differently from filesystem entries once you look past the syscall interface. An open() or read() on a file descriptor for a device will invoke the device driver, whereas for an actual file its filesystem is invoked, which may eventually call a storage device driver.

It would seem to my naive eyes that the overheading of opening a resource to read every 250ms would be an unnecessary strain on the kernel.

Yes it would since those open() and close() syscalls are unnecessary.

So it is valid to open, and then just use ioctl() to switch address whenever I need to,

Yes, that is the proper useage.

or must I close() the descriptor between reads and writes?

That is not necessary nor advised.

Upvotes: 5

Related Questions