69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("Argument error!\n");
exit(1);
}
int fd = open(argv[1],O_RDWR|O_NONBLOCK);
printf("fd %d\n",fd);
if(fd < 0)
{
fprintf(stderr,"open %s error:%s\n",argv[1],strerror(errno));
exit(1);
}
struct flock lock;
//给整个文件加锁
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
if(fcntl(fd,F_SETLK,&lock) < 0)
{
fprintf(stderr,"f_setlk error:%s\n",strerror(errno));
exit(1);
}
printf("pid:%d\n",getpid());
//等待输入,
getchar();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("Argument error!\n");
exit(1);
}
int fd = open(argv[1],O_RDWR|O_APPEND);
printf("fd:%d\n",fd);
if(fd < 0)
{
fprintf(stderr,"open error:%s\n",strerror(errno));
exit(1);
}
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
int flag;
if((flag = fcntl(fd,F_SETLK,&lock)) < 0)
{
//printf("flag:%d\n",flag);
fprintf(stderr,"set lock failure:%s\n",strerror(errno));
//exit(1);
}
fcntl(fd,F_GETLK,&lock);
if(lock.l_type == F_RDLCK)
printf("%d read lock is set by pid:%d\n",lock.l_type,lock.l_pid);
else if(lock.l_type == F_WRLCK)
printf("%d WRLOCK is set by pid:%d\n",lock.l_type,lock.l_pid);
else if(lock.l_type == F_UNLCK)
printf("none lock\n");
printf("l_start:%ld\n",lock.l_start);
printf("l_pid:%d\n",lock.l_pid);
char buffer[] = "hello world!";
if(write(fd,buffer,strlen(buffer)) < 0)
{
fprintf(stderr,"write error:%s\n",strerror(errno));
exit(1);
}
return 0;
}
Mandatory locking
(Non-POSIX.) The above record locks may be either advisory or mandatory, and are advisory by default.
Advisory locks are not enforced and are useful only between cooperating processes.
Mandatory locks are enforced for all processes. If a process tries to perform an incompatible access (e.g., read(2) or write(2)) on a file region that
has an incompatible mandatory lock, then the result depends upon whether the O_NONBLOCK flag is enabled for its open file description. If the O_NON-
BLOCK flag is not enabled, then system call is blocked until the lock is removed or converted to a mode that is compatible with the access. If the
O_NONBLOCK flag is enabled, then the system call fails with the error EAGAIN.
To make use of mandatory locks, mandatory locking must be enabled both on the file system that contains the file to be locked, and on the file itself.
Mandatory locking is enabled on a file system using the "-o mand" option to mount(8), or the MS_MANDLOCK flag for mount(2). Mandatory locking is
enabled on a file by disabling group execute permission on the file and enabling the set-group-ID permission bit (see chmod(1) and chmod(2)).
The Linux implementation of mandatory locking is unreliable. See BUGS below.