简体   繁体   中英

C - Shared library with management of the same file

I'd like to create shared library in C for linux, some abstract implementation of database management. Shared library whould be responsible for read file containing database and write differences into it. But I have no idea how to handle multiprocessing problems of file handling for this case eg.: App1 try to write differences into database file and App2 has currently opened file with database to read it. In the case of this example I'd like to inform app1 that file is currently open and delay write sequence until App2 will finish database file read.

I was thinking of using some mutual exclusion mechanisms or by using global enum variable to manage current file status, but after I read some of posts I understood that every application that uses shared library create it's own copy in memory and they don't share any memory section during work.

Shared library whould be responsible for read file containing database and write differences into it.

That is possible but quit complicated solution.

While you would need to make sure that multiple processes do not interfere with each other. It's possible to do so with file logs (see man flock ), and record locking in man fcntl but you must insure that multiple processes update disjoint file chunks "in place" (without resizing the file).

This is also prone to deadlocks -- if one of the processes takes a lock on a region and then goes into infinite loop, other processes may get stuck as well.

A much simpler solution involves client-server, where the server implements all writes and clients send it read and modify requests.

PS There are existing libraries implementing either approach. You will likely save yourself several months of development time using existing solutions.

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