10

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.

Moka
  • 988
  • 10
  • 10
  • this is user space code? – sr01853 Jan 30 '13 at 09:40
  • @Sibrajas: read and write are syscalls, which means that their implementation is inside the kernel. (well with the exception of vdso and vsyscalls, but dont worry about that) – Andrew Tomazos Jan 30 '13 at 09:43
  • May be this link on mandatory locking is useful. http://kernel.org/doc/Documentation/filesystems/mandatory-locking.txt – sr01853 Jan 30 '13 at 09:47
  • @user1131467 yes.i know that. i was just misguided with this text. how a syscall read/write was done(in first line). It could be edited as implemented. – sr01853 Jan 30 '13 at 09:50
  • 1
    possible duplicate of [Are POSIX' read() and write() system calls atomic?](http://stackoverflow.com/questions/14417806/are-posix-read-and-write-system-calls-atomic) – Hasturkun Jan 30 '13 at 17:06

2 Answers2

7

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.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
4

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.

Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319