Hello,
Your example demonstrates why opening the device file was designed to be exclusive.
Suppose it wasn't, and process A and B would both open the device file. As you surely know, accessing the registers involves two stages: seeking and then reading or writing. Should both processes attempt to access the hardware at the same time, they could both issue seek commands more or less simultaneously, so when they reached the stage of read/write, at least one of them would access the wrong address in the memory map. This would probably become a rare bug in your case, which makes it even worse.
So opening and closing the device file each time isn't a bad idea, if the access isn't intensive (temperature reading, for example, is usually done at a low sample rate). You may want to use flock() on the device file (or any other dedicated file) for preventing the failure of opening the device file. This way, the waiting process will block, rather than looping on trying to open the file. It's a bit more elegant.
The point is that no matter what way you go, if you want more than one process to access the device file, you need a mutex to ensure that they never access it at the same time. For example, a multithreaded program with a POSIX mutex. You may start with a single process that opens the device file, and then forks into two daemons.
And lastly, you may modify the driver to allow nonexclusive opening of the device file. If you read the xillybus_open function, you'll see that it depends on the wr_exclusive_open and rd_exclusive_open flags.
So you may change, in xilly_setupchannels():
- Code: Select all
exclusive_open = (chandesc[2] >> 7) & 0x01;
to
- Code: Select all
exclusive_open = 0;
But this is probably not a good idea, for the reasons mentioned above.
No matter how you twist and turn this, you'll need a locking mechanism. And a software lock is a matter of programming discipline: When used with care, they work great. In a hacky environment, hell breaks loose.
Another possibility to consider is to have separate device files for each process, in particular if they're dealing with separate functionalities.