How to block file when you reading (fopen) it

我的未来我决定 提交于 2019-12-12 02:18:35

问题


How to block file when you reading it (by fopen or open in linux), to prevent any modifications during reading?

What i have: 1 file with data; I want to read data from it in my function, so i use fopen():

FILE *file = fopen(fileName, "r"); Now i need something to block my file - any (or only current user's as variant) another process mustn't have any access (or only modify it as variant) to it until my function will allow them to do it

I suppose, i can do that using set chmod flags for them and setting them back after work; Or using open() function with special flags arguments, but it's not desirable because i would like to work with fgets() in function;

Is there any examples of how to do it?


回答1:


Yes, you can use flock to do this. However, since you want to open the file with fopen instead of open, you'll need to first get the file descriptor using fileno. For example:

FILE* f = fopen(...);
int fd = fileno(f);
// flock should return zero on success
flock(fd, LOCK_EX);

That would place an exclusive lock - if you want a shared lock, change LOCK_EX to LOCK_SH.



来源:https://stackoverflow.com/questions/26313856/how-to-block-file-when-you-reading-fopen-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!