对文件加锁,但里面的数据是错误的,先记录下,以后回来看,是缓冲造成的???。用共享内存操作是正确的
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
bool ngx_lock_fd(int fd)
{
printf("bg lock pid:%d\n", getpid());
struct flock fl;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = 0;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd,F_SETLK , &fl) == -1) {
printf("lock false pid %d\n", getpid());
return false;
}
printf("end lock pid:%d\n", getpid());
return true;
}
bool ngx_unlock_fd(int fd)
{
printf("bg ulock pid:%d\n", getpid());
struct flock fl;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = 0;
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &fl) == -1) {
return false;
}
printf("end ulock pid:%d\n", getpid());
return true;
}
int main()
{
int fd1;
fd1 = open("test.lock", O_WRONLY | O_CREAT, 0600);
pid_t fpid;
int key = getpid();
fpid = fork();
int count = 0;
int *pI = (int*) malloc(sizeof(int));
*pI = 0;
if(fpid == 0)
{
int shmid = shmget(key, 8, IPC_CREAT|0666|IPC_EXCL);
if(-1 == shmid)
{
printf("1 shmget failed");
exit(1);
}
// 映射共享内存,得到虚拟地址
void *p = shmat(shmid, 0, 0);
if((void*)-1 == p)
{
printf("shmat failed");
exit(2);
}
int *pp = (int*)p;
*pp = 0x1;
while(1)
{
if(ngx_lock_fd(fd1))
{
int fd;
fd = open("test", O_WRONLY | O_CREAT, 0600);
char buff[1024];
printf("c count:%d fpid:%d\n", count, fpid);
read(fd, &buff, 1024);
printf("r %s\n", buff);
ftruncate(fd, 0);
int i = ::atoi(buff);
snprintf(buff, 1024, "%d\n", ++i);
write(fd, buff, strlen(buff));
write(fd1, buff, strlen(buff));
printf("w %s\n", buff);
sync();
close(fd);
*pI = *pI + 1;
printf("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii: %d %d\n", *pI,getpid());
int *pp = (int*)p;
*pp = *pp + 0x1;
printf("ssssssssssssssssssssssssssssssssss: %d %d\n", *pp,getpid());
ngx_unlock_fd(fd1);
}
usleep(1000);
}
}
else
{
sleep(1);
int shmid = shmget(key, 0, 0);
if(-1 == shmid)
{
printf("shmget failed");
exit(1);
}
// 映射共享内存,得到虚拟地址
void *p = shmat(shmid, 0, 0);
if((void*)-1 == p)
{
printf("shmat failed");
exit(2);
}
while(1)
{
if(ngx_lock_fd(fd1))
{
int fd;
fd = open("test", O_WRONLY | O_CREAT, 0600);
char buff[1024];
printf("p count:%d fpid:%d\n", count, fpid);
read(fd, &buff, 1024);
printf("r %s\n", buff);
ftruncate(fd, 0);
int i = ::atoi(buff);
snprintf(buff, 1024, "%d\n", ++i);
write(fd, buff, strlen(buff));
write(fd1, buff, strlen(buff));
printf("w %s\n", buff);
sync();
close(fd);
*pI = *pI + 1;
printf("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii: %d %d\n", *pI,getpid());
int *pp = (int*)p;
*pp = *pp + 0x1;
printf("ssssssssssssssssssssssssssssssssss: %d %d\n", *pp,getpid());
ngx_unlock_fd(fd1);
}
usleep(1000);
}
}
return 0;
}