请问一个文件加锁的问题。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
main(int argc, char **argv)
{
int file;
struct flock lockss;
file = open(argv[1],O_RDWR);
if(!file)
{
printf("open %s error\n",argv[1]);
exit(0);
}
int n=0;
/*for(n=0; n<100; n++)
{
write(file,"a",1);
}*/
/*write(file, "\n", 1);*/
memset(&lockss, 0 , sizeof(lockss));
lockss.l_type = F_WRLCK;
lockss.l_whence = SEEK_SET;
lockss.l_start = 1;
lockss.l_len=100;
//lock1.l_pid=getpid();
int res;
res = fcntl(file, F_SETLKW, &lockss);
fflush(stdout);
//res = lockf(file, F_LOCK, 100);
if(res==-1)
{
printf("Process %d lock file %s failed.\n",getpid(), argv[1]);
exit(0);
}
else
{
printf("%s is locked by %d.\n",argv[1], getpid());
printf("res is %d \n",res);
}
sleep(60);
close(file)
}
我又用另一个程序去改写加锁部分为什么还能成功呢,加锁过程没报错。