我正在尝试在 unix 中学习编程 c。所以我通读了Beejs Guide并尝试了解有关文件锁定的更多信息。
所以我只是从他那里拿了一些代码示例,并试图读出文件是否被锁定,但每次我这样做时,我都会得到errno 22
它代表无效参数。所以我检查了我的代码是否有无效参数,但我找不到它们。有人可以帮助我吗?
我的错误发生在:
if( fcntl(fd, F_GETLK, &fl2) < 0 ) {
printf("Error occured!\n");
}
完整代码:
/*
** lockdemo.c -- shows off your system's file locking. Rated R.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
/* l_type l_whence l_start l_len l_pid */
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0 };
struct flock fl2;
int fd;
fl.l_pid = getpid();
if (argc > 1)
fl.l_type = F_RDLCK;
if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
perror("open");
exit(1);
}
printf("Press <RETURN> to try to get lock: ");
getchar();
printf("Trying to get lock...");
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("got lock\n");
printf("Press <RETURN> to release lock: ");
getchar();
fl.l_type = F_UNLCK; /* set to unlock same region */
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("Unlocked.\n");
printf("Press <RETURN> to check lock: ");
getchar();
if( fcntl(fd, F_GETLK, &fl2) < 0 ) {
printf("Error occured!\n");
}
else{
if(fl2.l_type == F_UNLCK) {
printf("no lock\n");
}
else{
printf("file is locked\n");
printf("Errno: %d\n", errno);
}
}
close(fd);
return 0;
}
我刚刚添加fl2
了底部的部分。