UNIX环境高级编程:记录上锁(fcntl函数)以及死锁检测
发布时间:2016-10-12 20:18:11 所属栏目:Unix 来源:网络整理
导读:一、记录锁 record locking 功能:当一个进程正在读或修改文件的某个部分时,它可以阻止其它进程修改同一文件区。 字节范围锁 byte-range locking 二、历史 flo
|
第二个程序是在在父进程中加写锁后,然后再子进程中测试能否继续加读写锁。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FILE_PATH "/home/huangcheng/data.txt"
#define FILE_MODE 0777
void lock_init(struct flock *lock, short type, short whence, off_t start, off_t len)
{
if (lock == NULL)
return;
lock->l_type = type;
lock->l_whence = whence;
lock->l_start = start;
lock->l_len = len;
}
int writew_lock(int fd)
{
if (fd < 0)
{
return -1;
}
struct flock lock;
lock_init(&lock, F_WRLCK, SEEK_SET, 0, 0);
if (fcntl(fd, F_SETLKW, &lock) != 0)
{
return -1;
}
return 0;
}
pid_t lock_test(int fd, short type, short whence, off_t start, off_t len)
{
struct flock lock;
lock_init(&lock, type, whence, start, len);
if (fcntl(fd, F_GETLK, &lock) == -1)
{
return -1;
}
if(lock.l_type == F_UNLCK)
return 0;
return lock.l_pid;
}
int unlock(int fd)
{
if (fd < 0)
{
return -1;
}
struct flock lock;
lock_init(&lock, F_UNLCK, SEEK_SET, 0, 0);
if (fcntl(fd, F_SETLKW, &lock) != 0)
{
return -1;
}
return 0;
}
int main()
{
int fd = open(FILE_PATH, O_RDWR | O_CREAT, FILE_MODE);
writew_lock(fd);
if (fork() == 0)
{
printf("child F_WRLCK return %dn",lock_test(fd, F_WRLCK, SEEK_SET, 0, 0));
printf("child F_RDLCK return %dn",lock_test(fd, F_RDLCK, SEEK_SET, 0, 0));
printf("child pid = %d and ppid = %dn",getpid(),getppid());
exit(0);
}
sleep(3);
unlock(fd);
return 0;
}
(编辑:佛山站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
