I came across the function pwrite() while studying UNIX programming. I read that

pwrite(file_descriptor,buf,bufsize,offset);

combines the following two into one atomic operation:

lseek(file_descriptor,offset,SEEK_SET);
write(file_descriptor,buf,bufsize);

But what if I need to append to a file?

  1. How will I find the value of offset that corresponds to the end of file?
  2. Even if I find the required offset value and call pwrite() using that value, it will not be an atomic operation ( as finding the offset and calling pwrite() may be interrupted by another process ).

So, my real question is, how can I atomically append to a file using pwrite()?

有帮助吗?

解决方案

On a complying implementation there is no way to use pwrite to make it work with O_APPEND. On linux pwrite ignores the offset for O_APPEND:

BUGS

POSIX requires that opening a file with the O_APPEND flag should have no affect on the location at which pwrite() writes data. However, on Linux, if a file is opened with O_APPEND, pwrite() appends data to the end of the file, regardless of the value of offset.

其他提示

You should open the file with the O_APPEND flag and write to it with write. According to the Open Group specification for write:

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.

Note that using high-level fwrite call might not keep the same guarantee of no intervening file modifications between seek and write.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top