I was looking at how a syscall read/write was done in linux, and i found this :
....
loff_t pos = file_pos_read(f.file);
ret = vfs_read(f.file, buf, count, &pos);
file_pos_write(f.file, pos);
fdput(f);
...`
My questions are :
Where did the locking go? I would have imaginated something like :
....
lock(f.file); // <-- lock file struct
loff_t pos = file_pos_read(f.file);
ret = vfs_read(f.file, buf, count, &pos);
file_pos_write(f.file, pos);
fdput(f);
unlock(f.file); // <-- unlock file struct
...
If multiple threads try to read/write at the same time, they could read/write at the same offset ?
If my understanding is correct, linux doesn't use any locking mechanism to protect the offset, is this POSIX compliant ?
I did look at the POSIX specification, and found nothing about this case.
Concurrency is the execution of the multiple instruction sequences at the same time. It happens in the operating system when there are several process threads running in parallel.
Filesystems usually deal with concurrency by using locking (i.e. by NOT dealing with concurrency). That is, it's assumed that if I'm writing to a file, then no one else will be writing to the same file at the same time.
Introduction to flock Command The flock command is also provided by the util-linux package. This utility allows us to manage advisory file locks in shell scripts or on the command line. The basic usage syntax is: flock FILE_TO_LOCK COMMAND.
11, flock() does not lock files over NFS (i.e., the scope of locks was limited to the local system). Instead, one could use fcntl(2) byte-range locking, which does work over NFS, given a sufficiently recent version of Linux and a server which supports locking. Since Linux 2.6.
Linux doesn't use any locking mechanism to protect multithread writing to a file.
You have to use your own mutex to protect your file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With