0
votes

I would like to read a structure from a device driver via an ioctl, change a value in the structure in userspace and then write it back. Is this possible to do atomically without some other process changing the structure inbetween read and write?

Could I lock the file descriptor (flock()) before the calls and unlock afterwards? Or, could I implement a lock and unlock ioctl command that sets an internal lock variable in the driver? What would happen if the process dies, how could the variable get cleared?

Could I use sysfs rather than ioctl to achieve the same effect?

1

1 Answers

0
votes

Not easily, and it is most likely the wrong approach.

Rather, I'd go with a "conditional move" approach. The userspace program retrieves the current value, modifies it, and then attaches the old value to the write IOCTL to be used as a condition:

Success:

read                        -> 5
write 10 if currently 5     -> okay

Failure:

read                        -> 5
... someone else changes it ...
write 10 if currently 5     -> nope

This way, the kernel does not have to keep any kind of state that needs to be cleaned up if the userspace program does not follow the protocol.