两个文件描述符指向同一个文件
使用 posix read() write() linux 调用,是否可以保证,如果我以串行方式写入一个文件描述符并读取另一个文件描述符,使得这两个操作彼此互斥......读文件描述符总是会看到写文件描述符最后写入的内容?
我相信情况确实如此,但我想确定一下,手册页对此没有太大帮助
Using the posix read() write() linux calls, is it guaranteed that if I write through one file descriptor and read through another file descriptor, in a serial fashion such that the two actions are mutually exclusive of each other... that my read file descriptor will always see what was written last by the write file descriptor?
i believe this is the case, but I want to make sure and the man page isn't very helpful on this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您从哪里获得两个文件描述符。如果它们来自 dup(2) 调用,则它们共享文件偏移量和状态,因此对其中一个执行 write(2) 将影响另一个的位置。另一方面,如果它们来自两个单独的 open(2) 调用,则每个调用都有自己的文件偏移量和状态。
文件描述符主要只是对内核文件结构的引用,并且该内核结构包含大部分状态。当您打开(2)一个文件时,您将获得一个新的内核文件结构和一个引用它的新文件描述符。当您 dup(2) 文件描述符(或通过 sendmsg 传递文件描述符)时,您将获得对同一内核文件结构的新引用。
It depends on where you got the two file descriptors. If they come from a dup(2) call, then they share file offset and status, so doing a write(2) on one will affect the position on the other. If, on the other hand, they come from two separate open(2) calls, each will have their own file offset and status.
A file descriptor is mostly just a reference to a kernel file structure, and it is that kernel structure that contains most of the state. When you open(2) a file, you get a new kernel file structure and a new file descriptor that refers to it. When you dup(2) a file descriptor (or pass a file descriptor through sendmsg), you get a new reference to the same kernel file struct.
如果它们都引用相同的文件描述,即您从“dup”或“dup2”(或通过
fork()
继承)获取它们,则这是保证的。This is guaranteed if they both refer to the same file description, aka you got them from "dup" or "dup2" (or inherited via
fork()
).当您使用
dup()
或dup2()
或fork()
时,文件表由两个文件描述符共享。
因此,如果您从一个文件描述符
写入
某些内容,然后再次通过其他文件描述符写入
某些内容,那么它会被附加而不是被覆盖。但是如果两个独立的进程打开一个文件,那么两个进程写入的数据可能会混合。
when you use
dup()
ordup2()
orfork()
,the file table is shared by both of the file descriptors.
so if you
write
something from one file descriptor , and againwrite
something through other file descriptor , then it is appended not overwritten.but if two independent process open one file , then the data written by both processes may get mixed.