Reputation: 1148
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.
Upvotes: 10
Views: 5062
Reputation: 43518
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.
Upvotes: 7
Reputation: 68638
It's your responsibility in a multithreaded application to serialize access to file descriptors. Across processes you can use the flock(2)
syscall to synchronize access to the same file.
The kernel won't crash if you access the same file from two different processes/threads, but it may overwrite or corrupt the file position and file data in an undefined way.
Upvotes: 4