我正在编写一个应用程序及其规范,我每次在其上写入时都需要锁定一个文件(该文件将为其他团队正在开发的其他应用程序读取):
我做了以下功能:
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;
}
我可以得到 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 */