is ok to open fifo with one FD and share it with multiple threads? or is it better to have multiple fds opened for the same fifo and share these fds with the threads? BTW, I'll be doing write and read.
The environment is linux, C, pthreads
Depends on what exactly you are going to do. Usually if you stick to the syscall-level interface (
Remember, that when there are multiple readers on fifo, random one of them will get the data and the switch from one reader to another may happen after any byte (because it depends on write granularity and internal implementation of the buffer in kernel), so you either need one fifo for each intended recipient or use single-byte messages.
From the OpenGroup Posix docs
3.289 Process An address space with one or more threads executing within that address space, and the required system resources for those threads. Note: Many of the system resources defined by POSIX.1-2008 are shared among all of the threads within a process. These include the process ID, the parent process ID, process group ID, session membership, real, effective, and saved set-user-ID, real, effective, and saved set-group-ID, supplementary group IDs, current working directory, root directory, file mode creation mask, and file descriptors.
There are two cases to consider:
In the first case, all of the threads will have the same file descriptor for the FIFO because that's how the OS manages that for you.
In the second case, if you share the file descriptor between the various
I'm pretty certain you're in the first case, not the second.
As Jan pointed out the
All else being equal, since the OS manages a lot of this for you I'd go with the multiple descriptors approach, even though it will likely result in the same file descriptor value being used. My primary reasoning is that it is less code you have to write and maintain. You can have a single routine that's called by each thread to get the descriptor. An additional benefit is that it sets you up well in case you need to fork to new processes instead of spawning child threads.
|show 2 more comments|