barfatchen
barfatchen

Reputation: 1698

two processes call open, one "W", another "r" at the same time. Error happens?

Suppose I have a process call A which call fopen(filename,"w"); every second, and write data in it, while process B call fopen(filename,"r") every 0.2 second and read data from it !!

In a very seldom situation, while A is writing data , before A fclose it, B process do fopen and read data from it. I think it has a sync problem!

Using Mutex is easy in thread, but I haven't tried mutex between processes. The data is only 400 bytes at most, I'd like to know what is the easy way to avoid a process writing data, and another process reading at the same time, or, while one process A fopen a file, another process B would wait until the process A fclose the file!

Upvotes: 0

Views: 1902

Answers (1)

ams
ams

Reputation: 25579

If you must use files (as @aix has said, there may be better ways), don't try to read files as they are being written or the results will be undefined.

Instead, write the data to a different filename, close it, and then move it to the right place (on Linux, use rename()).

If you don't like that, try using file locks. On Linux, at least, these don't actually prevent access to the file, they just act as inter-process mutexes. You don't say what OS you have, but for Linux, see man 2 flock.

Upvotes: 1

Related Questions