|
我看程序中有lockf 命令.自己写了2个程序一个是lockf,一个是flock.可是都必须在同一个进程才起作用.大家看我写的对么?
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/file.h>
int main()
{
int fd,return_int;
int num;
char *buf= "jingjing";
fd = open("bbb.txt",O_WRONLY); //bbb.txt中是一串字符串
printf("%d\n",fd);
//return_int = flock(fd,LOCK_EX);//加锁的语句
//sleep(65);
num = write(fd,buf,strlen(buf));
//return_int = flock(fd,LOCK_UN);
printf("%d\n",num);
close(fd);
return 0;
}//如果这样,字符串就写不进文件中.可是如果我在另一个程序中将文件加锁,在这个文件中向文件写数据还是能写进去!!
//write.c
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/file.h>
int main()
{
int fd,return_int;
int num;
char *buf= "jingjing";
fd = open("bbb.txt",O_WRONLY);
num = write(fd,buf,strlen(buf));
close(fd);
return 0;
}
//flock.c
#include<sys/file.h>
#include<fcntl.h>
int main()
{
int fd,return_int,return_inta;
fd = open("bbb.txt",O_WRONLY);
printf("fd is %d\n",fd);
return_int = flock(fd,LOCK_EX|LOCK_NB);
close(fd);
printf("%d\n",return_int);
return 0;
}//return_int 返回0
这样我就不太明白了.如果加锁只是在同一个进程才能生效??我的理解对么?????//lockf 例子基本同上
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv) {
int fildes;
int status;
int i=0;
fildes = open("bbb.txt",O_RDWR);
if (fildes == -1) {
fprintf(stderr, "open err=%d\n ", errno);
return -1;
}
status=lockf(fildes,F_TLOCK,(off_t)10000);
if (status !=0) {
fprintf(stderr, "err=%d\n ", errno);
} else {
fprintf(stderr, "lock ok\n ");
}
sleep(60);
close(fildes);
}
[ 本帖最后由 40943460 于 2008-6-18 11:43 编辑 ]
|