Day*_*ira 1 c file-io locking popen fcntl
我正在写一个应用程序及其在规范中我需要在每次写入时锁定文件(此文件将被其他团队正在处理的其他应用程序读取):
我做了以下功能:
int lock_file (int fd)
{
if (fd == -1)
return -1;
struct flock file_locker;
file_locker.l_type = F_WRLCK;
file_locker.l_whence = SEEK_SET;
file_locker.l_start = 0;
file_locker.l_len = 0; //lock the entire file
int locked = fcntl(fd, F_SETLK, &file_locker);
if (locked == -1){
/*handle errors*/
return 0;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
我可以获得1返回(意味着一切正常)但是当我做一个测试用例时,我可以写入锁定的文件Oo
测试代码是:
char *file = "lock_test_ok";
int fd = open(file, O_RDWR);
int locked = lock_file(fd);
/* call popen and try write 'ERROR' in the file */
/* if the file contains ERROR, than fail */
Run Code Online (Sandbox Code Playgroud)