关于多进程同时对文件读操作的问题
(2011-05-29 23:05:47)
今天看到fcnlt()函数,说设置一个文件的某一部位的记录锁设置为共享锁时,其他进程就可以同时对这个文件进行读操作,我起了一个疑问,如果不设置为共享锁(即读取锁),那就不能几个进程同时对这个文件进行读取吗?如果可以,那这个共享锁又有什么存在的意义?
于是我写了两个程序进行测试,验证我的想法,一个程序test.c创建并打开一个文件,向里面写入一句“hello guy ,you
look so cool today!
”,并一直读取这个文件,另一个程序read.c再来读取这个文件,看看能不能成功读取。程序如下:
程序test.c:
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>
int main()
{
int rc,wc,fd;
char buf[1024],rbuf[1024];
memset(buf,0,1024);
memset(rbuf,0,1024);
if((fd=open("test.txt",O_CREAT|O_RDWR,0666))<0)
{
perror("open");
exit(1);
}
strcpy(buf,"hello guy ,you look so cool today!");
if((wc=write(fd,buf,strlen(buf)))<0)
{
perror("write");
exit(1);
}
while(1)
{
lseek(fd,0,SEEK_SET);
if((rc=read(fd,rbuf,100))<0)
{
perror("read");