我正在研究以下示例,以了解 Windows 和 Linux 上的文件锁定。程序 1 使用 gcc 在 windows 和 linux 上运行。
但是第二个只能在 Linux 上运行。尤其是 winodws GCC 中的问题出现在结构 flock 声明中。我不知道我是否在这里遗漏了任何东西。此外,即使在第一个示例中关闭并取消链接文件以供下次运行时,该文件也未解锁。
程序 1:使用 GCC 在 Windows 上工作
来源:http://www.c.happycodings.com/Gnu-Linux/code9.html
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
if((fd = open("locked.file", O_RDWR|O_CREAT|O_EXCL, 0444)) == -1)
{
printf("[%d]: Error - file already locked ...\n", getpid());
}
else
{
printf("[%d]: Now I am the only one with access :-)\n", getpid());
close(fd);
unlink("locked.file");
}
程序 2:使用 GCC 在 Linux 上工作
来源:http://beej.us/guide/bgipc/output/html/multipage/flocking.html
#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 };
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");
close(fd);
return 0;
}
能否请您帮忙解决这个问题,如果可能的话,请提供这些场景中可移植代码的指南?
最佳答案
使用 C 运行时库可能很难获得这种操作的概率。对于这种事情,您确实需要使用特定于操作系统的代码。
但是,您可以通过检查和理解底层 C 运行时库实现来实现它。这些工具附带 GCC 运行时和 Microsofot 运行时的源代码。只需去看看它们是如何实现的。
请注意,在 Windows 上,您可以将 CRT 文件 I/O API 与 Windows 句柄一起使用。直接去看源码吧。
关于Windows 和 Linux 上的 C 文件锁定行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5800726/