7-3.c
来自「linux下一些命令的c语言的实现」· C语言 代码 · 共 41 行
C
41 行
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd;
struct flock fl;
fd = open("testfile", O_RDWR);
if (fd == –1)
/* Handle error */;
/* Make a non-blocking request to place a write lock on bytes 100–109 of testfile */
{
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
}
if (fcntl(fd, F_SETLK, &fl) == –1)
{
if (errno == EACCES || errno == EAGAIN) {
printf("Already locked by another process\n");
/* We can't get the lock at the moment */
} else {
/* Handle unexpected error */;
}
} else { /* Lock was granted... */
/* Perform I/O on bytes 100 to 109 of file */
/* Unlock the locked bytes */
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 100;
fl.l_len = 10;
if (fcntl(fd, F_SETLK, &fl) == –1)
/* Handle error */;
}
exit(EXIT_SUCCESS);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?