Linux 线程和文件描述符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6223776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Threads and file descriptors
提问by Lipika Deka
Am sorry for not doing my own research and asking it here. I am slightly short of time.
很抱歉没有做我自己的研究并在这里询问。我的时间有点短。
Is it possible to have two file descriptor table for two or more threads spwaned from a single thread. The two or more child threads are concurrently accessing same file, so is the offset for two different opens for same file from different threads, thread specific?
是否可以为从单个线程衍生的两个或多个线程提供两个文件描述符表。两个或多个子线程同时访问同一个文件,那么来自不同线程的同一个文件的两个不同打开的偏移量是特定于线程的吗?
Thanks
谢谢
采纳答案by cnicutar
The file descriptors are shared between the threads. If you want "thread specific" offsets, why not have each thread use a different file descriptor (open(2)
multiple times) ?
文件描述符在线程之间共享。如果您想要“特定于线程的”偏移量,为什么不让每个线程使用不同的文件描述符(open(2)
多次)?
回答by janneb
No, there is only one file descriptor table per process, and it's shared among all the threads.
不,每个进程只有一个文件描述符表,并且在所有线程之间共享。
From your problem description, you might want to look into the pread() and pwrite() functions.
根据您的问题描述,您可能需要查看 pread() 和 pwrite() 函数。
回答by ninjalj
In Linux, you can unshare()
the file descriptor table via the CLONE_FILES
flag, but I would advise against it.
在 Linux 中,您可以unshare()
通过CLONE_FILES
标志获取文件描述符表,但我不建议这样做。
回答by Aravindh
Try pread()/pwrite().
试试 pread()/pwrite()。
You can still share the same filedescriptor among multiple threads,i.e, parallel reads/writes to the same file is guaranteed to be atomic using pread()/pwrite() as you will need to specify offset and number of bytes to read/write respectively.
您仍然可以在多个线程之间共享相同的文件描述符,即,使用 pread()/pwrite() 保证对同一文件的并行读取/写入是原子的,因为您需要分别指定要读取/写入的偏移量和字节数.