How do I lock files using fopen()?

前端 未结 7 1928
时光取名叫无心
时光取名叫无心 2020-12-01 06:41

I wonder if there is any way to lock and unlock a file in Linux when I open a file using fopen (not open)?

Based on Stack Overflow question

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 07:10

    If you wish to implement your own lock simply, I suggest Rob's answer of using flock. If you wish to implement it in a complex manner, such as for high availability, you can try something like using a thread to touch a file at a regular interval. All other programs wanting to lock the file should also check the file to see if its update time has been updated in at another fixed, but larger interval (the larger part is important). This is probably overkill for most applications, but it handles things such as crashes, freezes, etc. much better than flock.

提交回复
热议问题