在Linux中,lockf()函数用于对打开的文件进行锁定操作,防止其他进程同时访问该文件。
lockf()函数的使用方法如下:
#include <unistd.h> int lockf(int fd, int cmd, off_t len); 下面是一个使用lockf()函数进行文件锁定的示例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main() { int fd; printf("Opening file...\n"); fd = open("testfile.txt", O_RDWR); if (fd == -1) { perror("open"); exit(1); } printf("Locking file...\n"); if (lockf(fd, F_LOCK, 0) == -1) { perror("lockf"); exit(1); } printf("File locked. Press any key to unlock.\n"); getchar(); printf("Unlocking file...\n"); if (lockf(fd, F_ULOCK, 0) == -1) { perror("lockf"); exit(1); } printf("File unlocked.\n"); close(fd); return 0; } 在上述示例中,首先使用open()函数打开了一个文件,然后使用lockf()函数进行文件锁定操作,锁定整个文件。然后等待用户按下任意键后,使用lockf()函数进行文件解锁操作。最后关闭文件并结束程序。