Gigi
Gigi

Reputation: 271

Multiple file descriptors to the same file, C

I have a multithreaded application that is opening and reading the same file (not writing). I am opening a different file descriptor for each thread (but they all point to the same file). Each thread then reads the file and may close it and open it again if EOF is reached. Is this ok? If I perform fclose() on a file descriptor does it affect the other file descritptors that point to the same file?

Upvotes: 8

Views: 10317

Answers (3)

gannon
gannon

Reputation: 61

For Linux systems you don't need multiple file descriptors to do this. You can share a single file descriptor and use pread to atomically do a seek / read operation without modifying the file descriptor at all.

Upvotes: 6

wallyk
wallyk

Reputation: 57784

That should work fine, provided each thread has its own file handle. Since you mention use of fclose(), that suggests you are also using fopen() in each thread and each thread only affects its own FILE * variable.

Is there a problem?

Upvotes: 0

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181430

That's ok. You can open all times you want the same file and each file descriptor will be independent from each other.

Upvotes: 3

Related Questions