检测文件是否在同一进程中被锁定

时间:2013-10-10 07:27:08

标签: c fcntl

我知道如何使用fcntl()锁定文件,如果其他进程想要读取或写入,则可能是错误。但我怎么知道我之前是否锁定了文件?

示例代码:

file_fd = open("file1", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

printf("file_can_read : %d\n", file_can_read(file_fd));
printf("file_can_write : %d\n", file_can_write(file_fd));

printf("write_lock test : %d\n", write_lock(file_fd));

printf("file_can_read : %d\n", file_can_read(file_fd));
printf("file_can_write : %d\n", file_can_write(file_fd));

file_fd2 = open("file1", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

printf("file2_can_read : %d\n", file_can_read(file_fd2));
printf("file2_can_write : %d\n", file_can_write(file_fd2));

printf("write_lock test 2: %d\n", write_lock(file_fd2));

printf("file2_can_read : %d\n", file_can_read(file_fd2));
printf("file2_can_write : %d\n", file_can_write(file_fd2));

以上功能:

define read_lock(fd) lock_reg((fd),F_RDLCK)
define write_lock(fd) lock_reg((fd),F_WRLCK)
define un_lock(fd) lock_reg((fd),F_UNLCK)

define file_can_read(fd) (lock_test((fd),F_RDLCK)==0)
define file_can_write(fd) (lock_test((fd),F_WRLCK)==0)

int lock_reg(int fd, int type){
    struct flock lock;
    lock.l_type = type;
    lock.l_start = 0;
    lock.l_whence = SEEK_SET;
    lock.l_len = 0;

    return (fcntl(fd, F_SETLKW, &lock));
}

int lock_test(int fd, int type){
    struct flock lock;
    lock.l_type = type;
    lock.l_start = 0;
    lock.l_whence = SEEK_SET;
    lock.l_len = 1;
    lock.l_pid = getpid();

    if(fcntl(fd, F_GETLK, &lock) < 0){ printf("fcntl error!\n"); return -1;}
    if(lock.l_type == F_UNLCK) return(0);
    return (lock.l_pid);
}

文件write_lock后返回值相同,如果其他文件描述符打开同一个文件,它仍然可以(我希望它失败),返回值仍然相同。

我试过fork它,但文件描述符表将被复制,但它仍然无法区分它们。

任何人都可以帮助我吗?

谢谢:)

0 个答案:

没有答案