C File Locking behavior on windows and Linux
I was looking into below examples for understanding files locking on windows and linux. The program 1 is working on both windows and linux with gcc.
But the second one is only working on Linux. Especially problem in winodws GCC is coming in the structure flock declaration. I dont know if I am missing any thing here. Also Even after I close and unlink the file in 1st example for the next run the file is not unlocked.
Program 1: Working on Windows with GCC
Source: 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_RD开发者_如何学PythonWR|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");
}
Program 2: Working on Linux with GCC
Source: 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;
}
Can you please help with this and if possible provide guidelines for portable code in these scenarios?
It will likely be difficult to get protabiltiy with this kind of operation using the C Runtime LIbrary. You really need to use OS specific code for this kind of thing.
But, you may be able to get this to work by inspecting and understanding the underlying C Runtime Library implimentations. The source code to both the GCC run times and the Microsofot run times come with the tools. Just go look and see how they are implimented.
Note that, on Windows, you can use the CRT file I/O APIs with Windows handles. Just go look at the source.
I would look into XPDEV specifically the file wrapper methods... they implement reasonable cross-platform locking.
精彩评论