Access Control on Device Files - Allow only one process to open at a time
Let's modify our /dev/kmsg driver to avoid multiple processes opening the device simultaneously to avoid any concurrency issue.
We will use atomic variables as a solution. You can learn more about atomic variables in my previous post.
Logic:
We will use atomic variables as a solution. You can learn more about atomic variables in my previous post.
Logic:
- Initialize the atomic value with 1
- In open function, decrement and check whether the value is zero, if zero then return success
- If the value is not zero, then increment the value and return EBUSY
- In release function, increment the value of atomic variable.
Code:
Sample Test Application:
Output:
Notes:
You can see while one thread was using the device and when the other thread tried to access it failed.
Also, from dmesg output, open was called twice and release only once
Comments
Post a Comment