|
|
linux操作系统是不是提供一种对打开文件的锁机制?
如果是的话,是不是fcntl函数在对打开文件进行锁的时候,就没有什么作用了?
这个函数还有什么其它的独特之处吗?若能举例则更好了,顺便帮看一下这个程序
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
int test(int fd,struct flock *lock)
{
//struct flock lock;
int stat=fcntl(fd,F_GETLK,lock);
if (stat<0)
{
perror("getlock failed");
return 0;
}
if (stat=0&&(*lock).l_type==F_UNLCK)
{
fprintf(stdout,"the file has not locked\n");
return 1;
}
if (stat=0&&(*lock).l_type==(F_WRLCK|F_RDLCK))
{
fprintf(stdout,"the file has lock by pid %d\n",(*lock).l_pid);
return 2;
}
}
int main()
{
int fd;
struct flock lock;
fd=open("/root/ch11/fcntl/lockit.c",O_RDONLY|O_WRONLY,0644);
if(fd<0)
{
fprintf(stdout,"open file failed\n");
perror("open");
}
int stat=test(fd,&lock);
switch(stat)
{
case 0:break;
case 1:
{
lock.l_type=F_RDLCK;
lock.l_whence=SEEK_SET;
lock.l_start=0;
lock.l_len=1;
int temp=fcntl(fd,F_SETLK,&lock);
if(temp<0)
{
perror("add read lock");
exit(EXIT_FAILURE);
}
fprintf(stdout,"lock the beginning charater\n");
break;
}
case 2:
{
int temp;
temp=fcntl(fd,F_UNLCK);
if (temp<0)
{
perror("unlock");
exit(EXIT_FAILURE);
}
fprintf(stdout,"unlock success\n");
break;
}
default:
break;
}
close(fd);
exit(EXIT_FAILURE);
}
这个程序可以编译和执行,但是就是提示fcntl的参数不对,为什么?? |
|