Locking and unlocking files using C API in Ubuntu LInux

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-13 05:38:08

问题


How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?


回答1:


It works like this:

#include <io.h>
#include <sys/file.h>
...
int f = open ("filename", O_RDONLY);
if (f < 0)
       error();
if (flock (f, LOCK_EX))
       error();
sleep (10);

if (flock (f, LOCK_UN))
       error();
...



回答2:


Use fcntl(2) to lock the file, then use alarm(2) to call your SIGALRM handler which will then unlock it.



来源:https://stackoverflow.com/questions/2058891/locking-and-unlocking-files-using-c-api-in-ubuntu-linux

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