I have a case where there are two processes which act on the same file - one as a writer and one as a reader. The file is a one line text file and the writer re-writes the line in a loop. reader reads the line. The pseudo code looks like this:
Writer Process
char buf[][18] = {
"xxxxxxxxxxxxxxxx",
"yyyyyyyyyyyyyyyy"
};
i = 0;
while (1) {
pwrite(fd, buf[i], 18, 0);
i = (i + 1) % 2;
}
Reader Process
while(1) {
pread(fd, readbuf, 18, 0);
//check if readbuf is either buf[0] or buf[1]
}
After a while of running both processes, I could see that the readbuf
is either xxxxxxxxxxxxxxxxyy
or yyyyyyyyyyyyyyyyxx
.
My understanding was that the write would be atomic for sizes upto 512 bytes. but from my experiment, it looks like the atomicity is only for 16 bytes.
man pages doesn't say anything about atomicity for normal files, it mentions only about pipe atomicity for 512 bytes.
I have tried this with tmpfs and ext4 and the result are the same. with O_SYNC
, ext4 writes become atomic and I understand it because writes don't return until it hits the disk, but O_SYNC
doesn't help for tmpfs (/dev/shm
).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…