【发布时间】:2014-06-24 12:18:24
【问题描述】:
我目前正在尝试实现一个并发服务器(即通过分叉新的子进程来处理多个进程)。
每个客户端都执行读/写请求以读取位于服务器中的 file.txt。我目前正在使用fnctl() 来处理同步,即。我可以进行多次读取,但只能进行一次写入。
这是我到目前为止所做的示例代码:
{
FILE *file = fopen("file.txt", "w+");
fd = fileno(file);
printf("\nThis is the file descriptor : %d\n", fd);
if(file == NULL)
printf("File cannot be opened");
printf("\nLocking!!!!");
//initliazing the flock structure
memset(&lock, 0, sizeof(lock)); //setting 0 as a value
lock.l_type = F_WRLCK; //F_RDLCK, F_WRLCK, F_UNLCK
lock.l_whence = SEEK_SET; //SEEK_SET, SEEK_CUR, SEEK_END
lock.l_start = 0; //offset from l_whence
lock.l_len = 0; //length, 0 = to EOF
lock.l_pid = getpid(); //the processes's PID
//placing a write lock on the file
fcntl(fd, F_SETLKW, &lock);
printf("\nLocked-------");
fwrite(buff + 1, 1, strlen(buff) - 1, file);
//lock_realease(&l);
printf("\nHit enter to unlock the file !");
getchar();
printf("\nFinished writing so we can unlock file !");
//Releasing lock
lock.l_type = F_UNLCK; //unlocks the region of the file
fcntl(fd, F_SETLKW,&lock);
printf("\nFile unlocked!");
}
如果我的方向正确,有人可以指导我吗?
【问题讨论】:
标签: c linux client-server