#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#if 0
int fcntl(int fd, int cmd, ... /* arg */ );
函数功能: 设置文件锁
参数说明:
fd : 文件描述符
cmd :命令
F_SETLKW :设置文件锁
struct flock {
...
short l_type; /* Type of lock: F_RDLCK,
F_WRLCK, F_UNLCK */
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
...
};
#endif
int main()
{
int fd;
fd = open("./data.txt", O_CREAT|O_WRONLY|O_TRUNC, 0777);
if(fd < 0)
{
perror("open");
return -1;
}
struct flock fk;
fk.l_type = F_WRLCK;
fk.l_whence = SEEK_SET;
fk.l_start = 0;
fk.l_len = 100;
fcntl(fd, F_SETLKW, &fk);
write(fd, "hello", 5);
sleep(20);
fk.l_type = F_UNLCK;
fcntl(fd, F_SETLKW, &fk);
close(fd);
return 0;
}