thread safety of read/pread system calls - c

I have few queries related to read()/pread() system calls in a multithreaded environment
I am using Mac-OSX which is freeBsd based , if that helps in any way
I am only using this file in read mode,and not read/write
And the language is c/c++
Suppose we have a file on disk
AAAABBBBCCCCDDDEEEE....
and 4 alphabets fit on one page of the file
So Page1:AAAA
Page2:BBBB
..... and so on
now i initiate a read system call from two different threads with the same file descriptor
my intension is to read first page from thread 1, second page from thread 2,..and so on.
read(fd,buff,sizeof(page));
From the man page i am given to understand that read will also increment the file pointer ,so definitely i am gonna get garbled responses like
ABCC ABBB .. etc (with no particular sequence )
to remedy this i can use pread()
"Pread() performs the same function, but reads from the speci-
fied position in the file without modifying the file pointer" // from man pages
But i am not sure whether using pread will actually help me in my objective , cause even though it does not increment the internal file pointer , there are no guarantees that the responses are not jumbled.
All of my data is page aligned and i want to read one page from each thread like
Thread 1 reads:AAAA
Thread 2 reads:BBBB
Thread 3 reads:CCCC ... without actually garbling the content ..
I also found a post Is it safe to read() from a file as soon as write() returns?
but it wasnt quite useful .
I am also not sure whether read() will actually have the problem, that i am thinking of.The file that i am reading is a binary file and hence i litle difficult to just quickly manually read and verify..
Any help will be appreciated

read and write change the position of the underlying open file. They are "thread safe" in the sense that your program will not have undefined behavior (crash or worse) if multiple threads perform IO on the same open file at once using them, but the order and atomicity of the operations could vary depending on the type of file and the implementation.
On the other hand, pread and pwrite do not change the position in the open file. They were added to POSIX for exactly the purpose you want: performing IO operations on the same open file from multiple threads or processes without the operations interfering with one another's position. You could still run into some trouble with ordering if you're mixing pread and pwrite (or multiple calls to pwrite) with overlapping parts of the file, but as long as you avoid that, they're perfectly safe for what you want to do.

fcntl advisory locks are locks on a range of the file. You may find this useful to serialize reads and writes to the same region while allowing concurrency on separate regions.
int rc;
struct flock f;
f.l_type = F_RDLCK; /* or F_WRLCK */
f.l_whence = SEEK_SET;
f.l_start = n;
f.l_len = 1;
while ((rc = fcntl(fd, F_SETLKW, &f)) == -1 && errno = EINTR)
;
if (rc == -1)
perror("fcntl(F_SETLKW)");
else {
/* do stuff */
f.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &f);
}
Multiple reader locks are permitted at a time, while a single writer lock blocks all others.
Be warned that all file locking mechanisms are subtly broken on some configurations on all platforms.

Share a mutex lock between the two threads, enable the lock in the thread before it reads, and unlock the lock when the correct read is complete. See pthread_mutex_create, pthread_mutex_lock, and pthread_mutex_unlock.

Related

Atomicity of `write(2)` on a file opened with the `O_APPEND` flag [duplicate]

Apparently POSIX states that
Either a file descriptor or a stream is called a "handle" on the
open file description to which it refers; an open file description
may have several handles. […] All activity by the application
affecting the file offset on the first handle shall be suspended
until it again becomes the active file handle. […] The handles need
not be in the same process for these rules to apply.
-- POSIX.1-2008
and
If two threads each call [the write() function], each call shall
either see all of the specified effects of the other call, or none
of them.
-- POSIX.1-2008
My understanding of this is that when the first process issues a
write(handle, data1, size1) and the second process issues
write(handle, data2, size2), the writes can occur in any order but
the data1 and data2 must be both pristine and contiguous.
But running the following code gives me unexpected results.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
die(char *s)
{
perror(s);
abort();
}
main()
{
unsigned char buffer[3];
char *filename = "/tmp/atomic-write.log";
int fd, i, j;
pid_t pid;
unlink(filename);
/* XXX Adding O_APPEND to the flags cures it. Why? */
fd = open(filename, O_CREAT|O_WRONLY/*|O_APPEND*/, 0644);
if (fd < 0)
die("open failed");
for (i = 0; i < 10; i++) {
pid = fork();
if (pid < 0)
die("fork failed");
else if (! pid) {
j = 3 + i % (sizeof(buffer) - 2);
memset(buffer, i % 26 + 'A', sizeof(buffer));
buffer[0] = '-';
buffer[j - 1] = '\n';
for (i = 0; i < 1000; i++)
if (write(fd, buffer, j) != j)
die("write failed");
exit(0);
}
}
while (wait(NULL) != -1)
/* NOOP */;
exit(0);
}
I tried running this on Linux and Mac OS X 10.7.4 and using grep -a
'^[^-]\|^..*-' /tmp/atomic-write.log shows that some writes are not
contiguous or overlap (Linux) or plain corrupted (Mac OS X).
Adding the flag O_APPEND in the open(2) call fixes this
problem. Nice, but I do not understand why. POSIX says
O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
but this is not the problem here. My sample program never does
lseek(2) but share the same file description and thus same file
offset.
I have already read similar questions on Stackoverflow but they still
do not fully answer my question.
Atomic write on file from two process does not specifically
address the case where the processes share the same file description
(as opposed to the same file).
How does one programmatically determine if “write” system call is atomic on a particular file? says that
The write call as defined in POSIX has no atomicity guarantee at all.
But as cited above it does have some. And what’s more,
O_APPEND seems to trigger this atomicity guarantee although it seems
to me that this guarantee should be present even without O_APPEND.
Can you explain further this behaviour ?
man 2 write on my system sums it up nicely:
Note that not all file systems are POSIX conforming.
Here is a quote from a recent discussion on the ext4 mailing list:
Currently concurrent reads/writes are atomic only wrt individual pages,
however are not on the system call. This may cause read() to return data
mixed from several different writes, which I do not think it is good
approach. We might argue that application doing this is broken, but
actually this is something we can easily do on filesystem level without
significant performance issues, so we can be consistent. Also POSIX
mentions this as well and XFS filesystem already has this feature.
This is a clear indication that ext4 -- to name just one modern filesystem -- doesn't conform to POSIX.1-2008 in this respect.
Edit: Updated Aug 2017 with latest changes in OS behaviours.
Firstly, O_APPEND or the equivalent FILE_APPEND_DATA on Windows means that increments of the maximum file extent (file "length") are atomic under concurrent writers. This is guaranteed by POSIX, and Linux, FreeBSD, OS X and Windows all implement it correctly. Samba also implements it correctly, NFS before v5 does not as it lacks the wire format capability to append atomically. So if you open your file with append-only, concurrent writes will not tear with respect to one another on any major OS unless NFS is involved.
This says nothing about whether reads will ever see a torn write though, and on that POSIX says the following about atomicity of read() and write() to regular files:
All of the following functions shall be atomic with respect to each
other in the effects specified in POSIX.1-2008 when they operate on
regular files or symbolic links ... [many functions] ... read() ...
write() ... If two threads each call one of these functions, each call
shall either see all of the specified effects of the other call, or
none of them. [Source]
and
Writes can be serialized with respect to other reads and writes. If a
read() of file data can be proven (by any means) to occur after a
write() of the data, it must reflect that write(), even if the calls
are made by different processes. [Source]
but conversely:
This volume of POSIX.1-2008 does not specify behavior of concurrent
writes to a file from multiple processes. Applications should use some
form of concurrency control. [Source]
A safe interpretation of all three of these requirements would suggest that all writes overlapping an extent in the same file must be serialised with respect to one another and to reads such that torn writes never appear to readers.
A less safe, but still allowed interpretation could be that reads and writes only serialise with each other between threads inside the same process, and between processes writes are serialised with respect to reads only (i.e. there is sequentially consistent i/o ordering between threads in a process, but between processes i/o is only acquire-release).
So how do popular OS and filesystems perform on this? As the author of proposed Boost.AFIO an asynchronous filesystem and file i/o C++ library, I decided to write an empirical tester. The results are follows for many threads in a single process.
No O_DIRECT/FILE_FLAG_NO_BUFFERING:
Microsoft Windows 10 with NTFS: update atomicity = 1 byte until and including 10.0.10240, from 10.0.14393 at least 1Mb, probably infinite as per the POSIX spec.
Linux 4.2.6 with ext4: update atomicity = 1 byte
FreeBSD 10.2 with ZFS: update atomicity = at least 1Mb, probably infinite as per the POSIX spec.
O_DIRECT/FILE_FLAG_NO_BUFFERING:
Microsoft Windows 10 with NTFS: update atomicity = until and including 10.0.10240 up to 4096 bytes only if page aligned, otherwise 512 bytes if FILE_FLAG_WRITE_THROUGH off, else 64 bytes. Note that this atomicity is probably a feature of PCIe DMA rather than designed in. Since 10.0.14393, at least 1Mb, probably infinite as per the POSIX spec.
Linux 4.2.6 with ext4: update atomicity = at least 1Mb, probably infinite as per the POSIX spec. Note that earlier Linuxes with ext4 definitely did not exceed 4096 bytes, XFS certainly used to have custom locking but it looks like recent Linux has finally fixed this problem in ext4.
FreeBSD 10.2 with ZFS: update atomicity = at least 1Mb, probably infinite as per the POSIX spec.
So in summary, FreeBSD with ZFS and very recent Windows with NTFS is POSIX conforming. Very recent Linux with ext4 is POSIX conforming only with O_DIRECT.
You can see the raw empirical test results at https://github.com/ned14/afio/tree/master/programs/fs-probe. Note we test for torn offsets only on 512 byte multiples, so I cannot say if a partial update of a 512 byte sector would tear during the read-modify-write cycle.
Some misinterpretation of what the standard mandates here comes from the use of processes vs. threads, and what that means for the "handle" situation you're talking about. In particular, you missed this part:
Handles can be created or destroyed by explicit user action, without affecting the underlying open file description. Some of the ways to create them include fcntl(), dup(), fdopen(), fileno(), and fork(). They can be destroyed by at least fclose(), close(), and the exec functions. [ ... ] Note that after a fork(), two handles exist where one existed before.
from the POSIX spec section you quote above. The reference to "create [ handles using ] fork" isn't elaborated on further in this section, but the spec for fork() adds a little detail:
The child process shall have its own copy of the parent's file descriptors. Each of the child's file descriptors shall refer to the same open file description with the corresponding file descriptor of the parent.
The relevant bits here are:
the child has copies of the parent's file descriptors
the child's copies refer to the same "thing" that the parent can access via said fds
file descriptors and file descriptions are not the same thing; in particular, a file descriptor is a handle in the above sense.
This is what the first quote refers to when it says "fork() creates [ ... ] handles" - they're created as copies, and therefore, from that point on, detached, and no longer updated in lockstep.
In your example program, every child process gets its very own copy which starts at the same state, but after the act of copying, these filedescriptors / handles have become independent instances, and therefore the writes race with each other. This is perfectly acceptable regarding the standard, because write() only guarentees:
On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written.
This means that while they all start the write at the same offset (because the fd copy was initialized as such) they might, even if successful, all write different amounts (there's no guarantee by the standard that a write request of N bytes will write exactly N bytes; it can succeed for anything 0 <= actual <= N), and due to the ordering of the writes being unspecified, the whole example program above therefore has unspecified results. Even if the total requested amount is written, all the standard above says that the file offset is incremented - it does not say it's atomically (once only) incremented, nor does it say that the actual writing of data will happen in an atomic fashion.
One thing is guaranteed though - you should never see anything in the file that has not either been there before any of the writes, or that had not come from either of the data written by any of the writes. If you do, that'd be corruption, and a bug in the filesystem implementation. What you've observed above might well be that ... if the final results can't be explained by re-ordering of parts of the writes.
The use of O_APPEND fixes this, because using that, again - see write(), does:
If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.
which is the "prior to" / "no intervening" serializing behaviour that you seek.
The use of threads would change the behaviour partially - because threads, on creation, do not receive copies of the filedescriptors / handles but operate on the actual (shared) one. Threads would not (necessarily) all start writing at the same offset. But the option for partial-write-success will still means that you may see interleaving in ways you might not want to see. Yet it'd possibly still be fully standards-conformant.
Moral: Do not count on a POSIX/UNIX standard being restrictive by default. The specifications are deliberately relaxed in the common case, and require you as the programmer to be explicit about your intent.
You're misinterpreting the first part of the spec you cited:
Either a file descriptor or a stream is called a "handle" on the open file description to which it refers; an open file description may have several handles. […] All activity by the application affecting the file offset on the first handle shall be suspended until it again becomes the active file handle. […] The handles need not be in the same process for these rules to apply.
This does not place any requirements on the implementation to handle concurrent access. Instead, it places requirements on an application not to make concurrent access, even from different processes, if you want well-defined ordering of the output and side effects.
The only time atomicity is guaranteed is for pipes when the write size fits in PIPE_BUF.
By the way, even if the call to write were atomic for ordinary files, except in the case of writes to pipes that fit in PIPE_BUF, write can always return with a partial write (i.e. having written fewer than the requested number of bytes). This smaller-than-requested write would then be atomic, but it wouldn't help the situation at all with regards to atomicity of the entire operation (your application would have to re-call write to finish).

Is write() safe to be called from multiple threads simultaneously?

Assuming I have opened dev/poll as mDevPoll, is it safe for me to call code like this
struct pollfd tmp_pfd;
tmp_pfd.fd = fd;
tmp_pfd.events = POLLIN;
// Write pollfd to /dev/poll
write(mDevPoll, &tmp_pfd, sizeof(struct pollfd));
...simultaneously from multiple threads, or do I need to add my own synchronisation primitive around mDevPoll?
Solaris 10 claims to be POSIX compliant. The write() function is not among the handful of system interfaces that POSIX permits to be non-thread-safe, so we can conclude that that on Solaris 10, it is safe in a general sense to call write() simultaneously from two or more threads.
POSIX also designates write() among those functions whose effects are atomic relative to each other when they operate on regular files or symbolic links. Specifically, it says that
If two threads each call one of these functions, each call shall either see all of the specified effects of the other call, or none of them.
If your writes were directed to a regular file then that would be sufficient to conclude that your proposed multi-thread actions are safe, in the sense that they would not interfere with one another, and the data written in one call would not be commingled with that written by a different call in any thread. Unfortunately, /dev/poll is not a regular file, so that does not apply directly to you.
You should also be aware that write() is not in general required to transfer the full number of bytes specified in a single call. For general purposes, one must therefore be prepared to transfer the desired bytes over multiple calls, by using a loop. Solaris may provide applicable guarantees beyond those expressed by POSIX, perhaps specific to the destination device, but absent such guarantees it is conceivable that one of your threads performs a partial write, and the next write is performed by a different thread. That very likely would not produce the results you want or expect.
It's not safe in theory, even though write() is completely thread-safe (barring implementation bugs...). Per the POSIX write() standard (emphasis mine):
.
The write() function shall attempt to write nbyte bytes from the
buffer pointed to by buf to the file associated with the open file
descriptor, fildes.
...
RETURN VALUE
Upon successful completion, these functions shall return the number of bytes actually written ...
There is no guarantee that you won't get a partial write(), so even if each individual write() call is atomic, it's not necessarily complete, so you could still get interleaved data because it may take more than one call to write() to completely write all data.
In practice, if you're only doing relatively small write() calls, you will likely never see a partial write(), with "small" and "likely" being indeterminate values dependent on your implementation.
I've routinely delivered code that uses unlocked single write() calls on regular files opened with O_APPEND in order to improve the performance of logging - build a log entry then write() the entire entry with one call. I've never seen a partial or interleaved write() result over almost a couple of decades of doing that on Linux and Solaris systems, even when many processes write to the same log file. But then again, it's a text log file and if a partial or interleaved write() does happen there would be no real damage done or even data lost.
In this case, though, you're "writing" a handful of bytes to a kernel structure. You can dig through the Solaris /dev/poll kernel driver source code at Illumos.org and see how likely a partial write() is. I'd suspect it's practically impossible - because I just went back and looked at the multiplatform poll class that I wrote for my company's software library a decade ago. On Solaris it uses /dev/poll and unlocked write() calls from multiple threads. And it's been working fine for a decade...
Solaris /dev/pool Device Driver Source Code Analysis
The (Open)Solaris source code can be found here: http://src.illumos.org/source/xref/illumos-gate/usr/src/uts/common/io/devpoll.c#628
The dpwrite() function is the code in the /dev/poll driver that actually performs the "write" operation. I use quotes because it's not really a write operation at all - data isn't transferred as much as the data in the kernel that represents the set of file descriptors being polled is updated.
Data is copied from user space into kernel space - to a memory buffer obtained with kmem_alloc(). I don't see any possible way that can be a partial copy. Either the allocation succeeds or it doesn't. The code can get interrupted before doing anything, as it wait for exclusive write() access to the kernel structures.
After that, the last return call is at the end - and if there's no error, the entire call is marked successful, or the entire call fails on any error:
995 if (error == 0) {
996 /*
997 * The state of uio_resid is updated only after the pollcache
998 * is successfully modified.
999 */
1000 uioskip(uiop, copysize);
1001 }
1002 return (error);
1003}
If you dig through Solaris kernel code, you'll see that uio_resid is what ends up being the value returned by write() after a successful call.
So the call certainly appears to be all-or-nothing. While there appear to be ways for the code to return an error on a file descriptor after successfully processing an earlier descriptor when multiple descriptors are passed in, the code doesn't appear to return any partial success indications.
If you're only processing one file descriptor at a time, I'd say the /dev/poll write() operation is completely thread-safe, and it's almost certainly thread-safe for "writing" updates to multiple file descriptors as there's no apparent way for the driver to return a partial write() result.

How to use pthread in C to prevent simultaneous read and write to a file on disk?

I am writing a program, which has one write thread, and a few read threads, that write/read to a file on disk. I wish that no write / read will happen at the same time. I found many examples which uses pthread mutex lock to protect memory array during write / read, such as declaring the protected memory array volatile.
volatile int array[NUMBER];
pthread_mutex_t locks[NUMBER];
pthread_mutex_lock(&locks[index]);
array[acct] -= SOME_NUMBER;
pthread_mutex_unlock(&locks[index]);
But I cannot find examples with using pthreads to protect files on disk.
volatile FILE* array[NUMBER]; ??
Can someone point me to the right direction? I wish write / read threads will not access the files on disk simultaneously.
Edit: I read more, and according to this post, it seems that multithreading does not work with disk IO.
According to the description, your problem is about protecting the files on the disk, not the stream descriptors(FILE*) that represents the files. You can try to use pthread's rwlock to synchronize concurrent access between multiple threads:
FILE *fp = fopen(...);
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
// read thread:
char buf[BUFLEN];
pthread_rwlock_rdlock(&rwlock);
fread(buf, sizeof buf, 1, fp);
pthread_rwlock_unlock(&rwlock);
// write thread:
pthread_rwlock_wrlock(&rwlock);
fwrite(buf, sizeof buf, 1, fp);
pthread_rwlock_unlock(&rwlock);
Note that this protect the file from accessed by multiple threads in the same process, this does not protect it from accessing by multiple processes on the system.
It depends on what you mean by "will not access the files on disk simultaneously". Since you talk about pthreads, it means you're on a POSIX system. POSIX already has certain guarantees about file access by multiple processes and threads.
If you use the raw system calls read and write you're for example guaranteed that writes will be atomic. This means that if a read and write happen simultaneously (meaning: you don't know which starts first), the read will either see the entire change to the file that the write did or none of it (there might be some exceptions here on errors). Of course there are problems with reading and writing the same file descriptor by multiple threads since read/write updates the offset where the next read/write will happen. So doing an lseek and then write is unsafe if some other thread can touch the file descriptor between the seek and the write. But for that you have the system calls pread and pwrite that guarantee that the seek+read/write will be atomic.
So by just going on this part of your problem description:
one write thread, and a few read threads, that write/read to a file on disk. I wish that no write / read will happen at the same time.
this is already guaranteed by the operating system. The problem I think is that "at the same time" is a very vague requirement because almost nothing that accesses a shared resource (like a file or even memory) happens at the same time. When thinking about threads or just about any concurrency you need to frame the problem in terms of what needs to happen before/after some other thing.

Atomicity of `write(2)` to a local filesystem

Apparently POSIX states that
Either a file descriptor or a stream is called a "handle" on the
open file description to which it refers; an open file description
may have several handles. […] All activity by the application
affecting the file offset on the first handle shall be suspended
until it again becomes the active file handle. […] The handles need
not be in the same process for these rules to apply.
-- POSIX.1-2008
and
If two threads each call [the write() function], each call shall
either see all of the specified effects of the other call, or none
of them.
-- POSIX.1-2008
My understanding of this is that when the first process issues a
write(handle, data1, size1) and the second process issues
write(handle, data2, size2), the writes can occur in any order but
the data1 and data2 must be both pristine and contiguous.
But running the following code gives me unexpected results.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
die(char *s)
{
perror(s);
abort();
}
main()
{
unsigned char buffer[3];
char *filename = "/tmp/atomic-write.log";
int fd, i, j;
pid_t pid;
unlink(filename);
/* XXX Adding O_APPEND to the flags cures it. Why? */
fd = open(filename, O_CREAT|O_WRONLY/*|O_APPEND*/, 0644);
if (fd < 0)
die("open failed");
for (i = 0; i < 10; i++) {
pid = fork();
if (pid < 0)
die("fork failed");
else if (! pid) {
j = 3 + i % (sizeof(buffer) - 2);
memset(buffer, i % 26 + 'A', sizeof(buffer));
buffer[0] = '-';
buffer[j - 1] = '\n';
for (i = 0; i < 1000; i++)
if (write(fd, buffer, j) != j)
die("write failed");
exit(0);
}
}
while (wait(NULL) != -1)
/* NOOP */;
exit(0);
}
I tried running this on Linux and Mac OS X 10.7.4 and using grep -a
'^[^-]\|^..*-' /tmp/atomic-write.log shows that some writes are not
contiguous or overlap (Linux) or plain corrupted (Mac OS X).
Adding the flag O_APPEND in the open(2) call fixes this
problem. Nice, but I do not understand why. POSIX says
O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
but this is not the problem here. My sample program never does
lseek(2) but share the same file description and thus same file
offset.
I have already read similar questions on Stackoverflow but they still
do not fully answer my question.
Atomic write on file from two process does not specifically
address the case where the processes share the same file description
(as opposed to the same file).
How does one programmatically determine if “write” system call is atomic on a particular file? says that
The write call as defined in POSIX has no atomicity guarantee at all.
But as cited above it does have some. And what’s more,
O_APPEND seems to trigger this atomicity guarantee although it seems
to me that this guarantee should be present even without O_APPEND.
Can you explain further this behaviour ?
man 2 write on my system sums it up nicely:
Note that not all file systems are POSIX conforming.
Here is a quote from a recent discussion on the ext4 mailing list:
Currently concurrent reads/writes are atomic only wrt individual pages,
however are not on the system call. This may cause read() to return data
mixed from several different writes, which I do not think it is good
approach. We might argue that application doing this is broken, but
actually this is something we can easily do on filesystem level without
significant performance issues, so we can be consistent. Also POSIX
mentions this as well and XFS filesystem already has this feature.
This is a clear indication that ext4 -- to name just one modern filesystem -- doesn't conform to POSIX.1-2008 in this respect.
Edit: Updated Aug 2017 with latest changes in OS behaviours.
Firstly, O_APPEND or the equivalent FILE_APPEND_DATA on Windows means that increments of the maximum file extent (file "length") are atomic under concurrent writers. This is guaranteed by POSIX, and Linux, FreeBSD, OS X and Windows all implement it correctly. Samba also implements it correctly, NFS before v5 does not as it lacks the wire format capability to append atomically. So if you open your file with append-only, concurrent writes will not tear with respect to one another on any major OS unless NFS is involved.
This says nothing about whether reads will ever see a torn write though, and on that POSIX says the following about atomicity of read() and write() to regular files:
All of the following functions shall be atomic with respect to each
other in the effects specified in POSIX.1-2008 when they operate on
regular files or symbolic links ... [many functions] ... read() ...
write() ... If two threads each call one of these functions, each call
shall either see all of the specified effects of the other call, or
none of them. [Source]
and
Writes can be serialized with respect to other reads and writes. If a
read() of file data can be proven (by any means) to occur after a
write() of the data, it must reflect that write(), even if the calls
are made by different processes. [Source]
but conversely:
This volume of POSIX.1-2008 does not specify behavior of concurrent
writes to a file from multiple processes. Applications should use some
form of concurrency control. [Source]
A safe interpretation of all three of these requirements would suggest that all writes overlapping an extent in the same file must be serialised with respect to one another and to reads such that torn writes never appear to readers.
A less safe, but still allowed interpretation could be that reads and writes only serialise with each other between threads inside the same process, and between processes writes are serialised with respect to reads only (i.e. there is sequentially consistent i/o ordering between threads in a process, but between processes i/o is only acquire-release).
So how do popular OS and filesystems perform on this? As the author of proposed Boost.AFIO an asynchronous filesystem and file i/o C++ library, I decided to write an empirical tester. The results are follows for many threads in a single process.
No O_DIRECT/FILE_FLAG_NO_BUFFERING:
Microsoft Windows 10 with NTFS: update atomicity = 1 byte until and including 10.0.10240, from 10.0.14393 at least 1Mb, probably infinite as per the POSIX spec.
Linux 4.2.6 with ext4: update atomicity = 1 byte
FreeBSD 10.2 with ZFS: update atomicity = at least 1Mb, probably infinite as per the POSIX spec.
O_DIRECT/FILE_FLAG_NO_BUFFERING:
Microsoft Windows 10 with NTFS: update atomicity = until and including 10.0.10240 up to 4096 bytes only if page aligned, otherwise 512 bytes if FILE_FLAG_WRITE_THROUGH off, else 64 bytes. Note that this atomicity is probably a feature of PCIe DMA rather than designed in. Since 10.0.14393, at least 1Mb, probably infinite as per the POSIX spec.
Linux 4.2.6 with ext4: update atomicity = at least 1Mb, probably infinite as per the POSIX spec. Note that earlier Linuxes with ext4 definitely did not exceed 4096 bytes, XFS certainly used to have custom locking but it looks like recent Linux has finally fixed this problem in ext4.
FreeBSD 10.2 with ZFS: update atomicity = at least 1Mb, probably infinite as per the POSIX spec.
So in summary, FreeBSD with ZFS and very recent Windows with NTFS is POSIX conforming. Very recent Linux with ext4 is POSIX conforming only with O_DIRECT.
You can see the raw empirical test results at https://github.com/ned14/afio/tree/master/programs/fs-probe. Note we test for torn offsets only on 512 byte multiples, so I cannot say if a partial update of a 512 byte sector would tear during the read-modify-write cycle.
Some misinterpretation of what the standard mandates here comes from the use of processes vs. threads, and what that means for the "handle" situation you're talking about. In particular, you missed this part:
Handles can be created or destroyed by explicit user action, without affecting the underlying open file description. Some of the ways to create them include fcntl(), dup(), fdopen(), fileno(), and fork(). They can be destroyed by at least fclose(), close(), and the exec functions. [ ... ] Note that after a fork(), two handles exist where one existed before.
from the POSIX spec section you quote above. The reference to "create [ handles using ] fork" isn't elaborated on further in this section, but the spec for fork() adds a little detail:
The child process shall have its own copy of the parent's file descriptors. Each of the child's file descriptors shall refer to the same open file description with the corresponding file descriptor of the parent.
The relevant bits here are:
the child has copies of the parent's file descriptors
the child's copies refer to the same "thing" that the parent can access via said fds
file descriptors and file descriptions are not the same thing; in particular, a file descriptor is a handle in the above sense.
This is what the first quote refers to when it says "fork() creates [ ... ] handles" - they're created as copies, and therefore, from that point on, detached, and no longer updated in lockstep.
In your example program, every child process gets its very own copy which starts at the same state, but after the act of copying, these filedescriptors / handles have become independent instances, and therefore the writes race with each other. This is perfectly acceptable regarding the standard, because write() only guarentees:
On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written.
This means that while they all start the write at the same offset (because the fd copy was initialized as such) they might, even if successful, all write different amounts (there's no guarantee by the standard that a write request of N bytes will write exactly N bytes; it can succeed for anything 0 <= actual <= N), and due to the ordering of the writes being unspecified, the whole example program above therefore has unspecified results. Even if the total requested amount is written, all the standard above says that the file offset is incremented - it does not say it's atomically (once only) incremented, nor does it say that the actual writing of data will happen in an atomic fashion.
One thing is guaranteed though - you should never see anything in the file that has not either been there before any of the writes, or that had not come from either of the data written by any of the writes. If you do, that'd be corruption, and a bug in the filesystem implementation. What you've observed above might well be that ... if the final results can't be explained by re-ordering of parts of the writes.
The use of O_APPEND fixes this, because using that, again - see write(), does:
If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation.
which is the "prior to" / "no intervening" serializing behaviour that you seek.
The use of threads would change the behaviour partially - because threads, on creation, do not receive copies of the filedescriptors / handles but operate on the actual (shared) one. Threads would not (necessarily) all start writing at the same offset. But the option for partial-write-success will still means that you may see interleaving in ways you might not want to see. Yet it'd possibly still be fully standards-conformant.
Moral: Do not count on a POSIX/UNIX standard being restrictive by default. The specifications are deliberately relaxed in the common case, and require you as the programmer to be explicit about your intent.
You're misinterpreting the first part of the spec you cited:
Either a file descriptor or a stream is called a "handle" on the open file description to which it refers; an open file description may have several handles. […] All activity by the application affecting the file offset on the first handle shall be suspended until it again becomes the active file handle. […] The handles need not be in the same process for these rules to apply.
This does not place any requirements on the implementation to handle concurrent access. Instead, it places requirements on an application not to make concurrent access, even from different processes, if you want well-defined ordering of the output and side effects.
The only time atomicity is guaranteed is for pipes when the write size fits in PIPE_BUF.
By the way, even if the call to write were atomic for ordinary files, except in the case of writes to pipes that fit in PIPE_BUF, write can always return with a partial write (i.e. having written fewer than the requested number of bytes). This smaller-than-requested write would then be atomic, but it wouldn't help the situation at all with regards to atomicity of the entire operation (your application would have to re-call write to finish).

Set pipe buffer size

I have a C++ multithreaded application which uses posix pipes in order to perform inter thread communications efficiently (so I don't have to get crazy with deadlocks).
I've set the write operation non-blocking, so the writer will get an error if there is not enough space in the buffer to write.
if((pipe(pipe_des)) == -1)
throw PipeException();
int flags = fcntl(pipe_des[1], F_GETFL, 0); // set write operation non-blocking
assert(flags != -1);
fcntl(pipe_des[1], F_SETFL, flags | O_NONBLOCK);
Now I'd wish to set the pipe buffer size to a custom value (one word in the specific case).
I've googled for it but I was not able to find anything useful. Is there a way (possibly posix compliant) to do it?
Thanks
Lorenzo
PS: I'm under linux (if it may be useful)
Since you mentioned you are on Linux and may not mind non-portability, you may be interested in the file descriptor manipulator F_SETPIPE_SZ, available since Linux 2.6.35.
int pipe_sz = fcntl(pipe_des[1], F_SETPIPE_SZ, sizeof(size_t));
You'll find that pipe_sz == getpagesize() after that call, since the buffer cannot be made smaller than the system page size. See fcntl(2).
I googled "linux pipe buffer size" and got this as the top link. Basically, the limit is 64Kb and is hard coded.
Edit The link is dead and it was probably wrong anyway. The Linux pipe(7) man page says this:
A pipe has a limited capacity. If the pipe is full, then a write(2)
will block or fail, depending on whether the O_NONBLOCK flag is set
(see below). Different implementations have different limits for the
pipe capacity. Applications should not rely on a particular
capacity: an application should be designed so that a reading process
consumes data as soon as it is available, so that a writing process
does not remain blocked.
In Linux versions before 2.6.11, the capacity of a pipe was the same
as the system page size (e.g., 4096 bytes on i386). Since Linux
2.6.11, the pipe capacity is 16 pages (i.e., 65,536 bytes in a system
with a page size of 4096 bytes). Since Linux 2.6.35, the default
pipe capacity is 16 pages, but the capacity can be queried and set
using the fcntl(2) F_GETPIPE_SZ and F_SETPIPE_SZ operations. See
fcntl(2) for more information.
Anyway, the following still applies IMO:
I'm not sure why you are trying to set the limit lower, it seems like a strange idea to me. If you want the writer to wait until the reader has processed what it has written, you should use a pipe in the other direction for the reader to send back an ack.
You could use a shared-memory area( System V - like ) of two words, one for sending data and the other for receiving data, and implement your pipes with them.
other solutions, as you may found previously, are about recompiling the kernel as you would like to have it, but it is not the case, I suppose.
Ciao!

Resources