Reputation: 95
I have one file named "data.txt" with always 50 bytes of data.
I have two threads.
The first thread, read content from byte 0 to byte 50:
while(1){
char buf[50];
FILE* fp = fopen("data.txt","r");
fread(buf,1,50,fp);
/* process data */
fclose(fp);
}
The second thread, append data to the file (= always after the first 50 bytes):
while(1){
FILE* fp = fopen("data.txt","a");
fwrite("hello\n",1,6,fp);
fclose(fp);
}
Is this solution thread-safe and portable ? (no segmentation fault, no data inconsistency, ...)
Upvotes: 1
Views: 592
Reputation: 7990
There is only one position indicator associated the file stream, the problem is if you open the file in append mode, the position indicator go to the end of file before every write. You can reposition the position indicator with fseek()
for reading, but as soon as you write to the file, the position indicator goes back to the end of file.
EDIT:
It's OK since each file descriptor in each thread will be independent from each other.
Upvotes: 0
Reputation: 16017
As I wrote in your other, related post, to my best knowledge it shouldn't crash. Whether it writes and reads and reads properly I don't know.
If you are on a POSIX system: Have you considered using a fifo (cf. http://man7.org/linux/man-pages/man7/fifo.7.html)? I have the impression that the file system is just a helper for your underlying communication demand, i.e. the actual file is not important.
Upvotes: 1