文件描述符上的原子追加,但偏移量是多少?

发布于 2024-10-03 08:15:16 字数 214 浏览 4 评论 0原文

在 unistd.h 中

使用带有 O_APPEND 标志的 open() 总是可以将原子写入添加到文件末尾...

这很好,但是如果我需要知道它原子附加到文件的偏移量怎么办? .?

我意识到 O_APPEND 通常用于日志文件,但我实际上想知道它自动附加的文件中的偏移量。

我没有看到任何明显的方法来做到这一点..?有谁知道吗?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪菊怪哟 2024-10-10 08:15:16

要获取文件描述符中的当前位置,请使用 lseek() 以及偏移量 0SEEK_CUR

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

请注意,如果描述符以其他方式(即通过 socket())打开,这不会为您提供可靠的结果。

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, i.e. via socket().

尴尬癌患者 2024-10-10 08:15:16

文件被写入到文件打开时进程获得的文件偏移量处。如果另一个进程在打开和写入之间写入该文件,则该文件的内容是不确定的。

处理多进程写入单个文件的正确方法是,所有进程都使用 O_APPEND 标志打开文件,获取排他锁,一旦获取锁,在写入文件之前先查找文件末尾,然后最后关闭文件以释放锁。

如果要在写入之间保持文件打开状态,请通过使用 O_APPEND 标志打开文件来启动该过程。本例中的写入循环是获取排他锁、查找文件末尾、写入文件并释放锁。

如果您确实需要文件位置, lseek 将返回文件偏移量调用时的调用者文件描述符。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文