- 论坛徽章:
- 0
|
我试图用fcntl(..., F_GETLK,...)来测试一个文件是否被锁。发现一个进程锁文件,
一个进程测试是否锁是可行的。但是如果锁文件,测试是否锁了,这俩个动作在同一进程中
测试结果就失效了。不知道大伙有没测试出文件被同一进程上锁的好方法。也就是在下面的
输出中,程序不会走“parent lock can be successful”这个分支,而走
“parent lock failed for lock-write by。。。” 或者
“parent lock failed for lock-read by 。。。”
先谢谢大家了。
./a.out
I am the child process, my process id is 16408
I am the parent process, my process id is 16407
parent locking..
parent lock can be successful
child testing lock...
child lock failed for lock-read by 16407
#include<stdio.h>
#include<sys/file.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
FILE *fp;
int fd;
struct flock lock;
struct flock getedLock;
pid_t pid;
getedLock.l_whence = lock.l_whence = 0;
getedLock.l_start = lock.l_start = 0;
getedLock.l_len = lock.l_len = 0L;
getedLock.l_type = F_WRLCK;
if (!(fp = fopen("testlock.cel","r+"))) {
printf("can't open file.\n");
return 1;
}
fd = fileno(fp);
pid = fork();
if (pid < 0) {
printf("error in fork!");
} else if (pid == 0) {
printf("I am the child process, my process id is %d\n",getpid());
sleep(3);
printf("child testing lock...\n");
getedLock.l_pid = getpid();
if(fcntl(fd, F_GETLK, &getedLock) == -1) {
printf("Child geting lock failed\n");
return 0;
}
if (getedLock.l_type == F_WRLCK) {
printf("child lock failed for lock-write by %d\n", getedLock.l_pid);
} else if (getedLock.l_type == F_RDLCK) {
printf("child lock failed for lock-read by %d\n", getedLock.l_pid);
} else if (getedLock.l_type == F_UNLCK) {
printf("child lock can be successful\n");
}
sleep(3);
return 0;
} else {
printf("I am the parent process, my process id is %d\n",getpid());
printf("parent locking..\n");
lock.l_pid = getpid();
lock.l_type = F_RDLCK;
if(fcntl(fd, F_SETLK, &lock) == -1 ) {
printf("Parent process failed to lock file to %s\n",(lock.l_type == F_WRLCK) ? "write" : "read");
return 0;
}
if(fcntl(fd, F_GETLK, &getedLock) == -1) {
printf("Child geting lock failed\n");
return 0;
}
if (getedLock.l_type == F_WRLCK) {
printf("parent lock failed for lock-write by %d\n", getedLock.l_pid);
} else if (getedLock.l_type == F_RDLCK) {
printf("parent lock failed for lock-read by %d\n", getedLock.l_pid);
} else if (getedLock.l_type == F_UNLCK) {
printf("parent lock can be successful\n");
}
sleep(10);
}
return 0;
} |
|