简体   繁体   中英

atomic append on a file descriptor, but at what offset?

in unistd.h

using open() with the O_APPEND flag gives atomic writes always to the end of the file...

this is great and all, but what if i need to know the offset at which it atomically appended to the file...?

i realize O_APPEND is often used for log files, but I'd actually like to know at what offset in the file it atomically appended.

I don't see any obvious way to do this..? Does anyone know?

Thanks

To get the current position in a file descriptor, use lseek() with offset 0 and whence SEEK_CUR .

int fd = open(...);
if (fd) {
    off_t positionWhereAppendingBegins = lseek(fd, 0, SEEK_CUR);
    write(...);
    close(fd);
}

Note that this will not give you reliable results if the descriptor was opened some other way, ie via socket() .

The file is written to at the file offset as obtained by the process when the file was opened. If another process writes to the file between the open and the write, then contents of the file are indeterminate.

The correct method of handling multiple process writing to a single file is for all processes to open the file with the O_APPEND flag, obtain an exclusive lock and once the lock is obtained, seek to the end of the file before writing to the file, and finally close the file to release the lock.

If you want to keep the file open between writes, initiate the process by opening the file with the O_APPEND flag. The writing loop in this case is obtain the exclusive lock, seek to the end of the file, write to the file and release the lock.

If you really need the file position, lseek will return the file offset of the callers file descriptor at the time of the call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM