简体   繁体   中英

Safe access to file from two processes

Suppose I have two processes. One always resides in memory and periodically reads some settings from a file on a disk. If it detects that settings was changed then it applies them.

The other process runs under command line by demand and modifies the settings. Thus the first process only read the file and never write to it while the second can only write to the file.

Should I synchronize the access to the file to ensure that the first process will always get consistent settings ie before or after modifications not some intermediate contents? If yes, what is the simplest way to do this in C++.

I'm interested mainly in cross-platform ways. But also curious about Windows- and/or Linux-specific ones.

Use a named semaphore and require either process to hold the semaphore before editing the file on disk. Named semaphores can be connected to by any running application.

Look at man 7 sem_overview for more information on named semaphores on linux machines.

The closest equivalent for windows I can find is http://msdn.microsoft.com/en-us/library/windows/desktop/ms682438(v=vs.85).aspx

You are using C++ so your first option should be to check through the usual cross-platform libs - POCO , Boost , ACE , and so forth to see if there is anything that already does what you require.

You really have two separate issues: (1) file synchronization and (2) notification.

On Linux to avoid having your daemon constantly polling to see if a file has changed you can use inotify calls and set up events that will tell you when the file has been changed by the command line program. It might be simplest to look for IN_CLOSE_WRITE events since a CL prog will presumably be opening, changing, and closing the file.

For synchronization, since you are in control of both programs, you can just use file or record locking eg lockf , flock or fcntl .

The most obvious solution is to open the file in exclusive mode. If the file can not be opened, wait some time and try to open the file again. This will prevent possible access/modification conflicts.

The benefit of this approach is that it's simple and doesn't have significant drawbacks.

Of course you could use some synchronization primitives (Mutex, Semaphore depending on the OS) but this would be an overkill in your scenario, when speedy response is not required (waiting 200 msec between open attempts is fine, and writing of config file won't take more).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM