0
我目前正试图实现一个并发服务器(即通过派生新子进程来处理多个进程)。使用fnctl()锁定和解锁文件进行读写(多个进程)
每个客户端执行读取/写入请求以从位于服务器中的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!");
}
有人能指导我,如果我在正确的方向吗?
你能给我一些关于如何执行这样的错误处理和请等待的指导吗? – user3770009
对于错误处理,您需要检查您所调用功能的手册。通常,你必须检查你调用的所有函数的返回值。对于等待而言,这更复杂。你需要找到一个功能,让你的孩子睡觉和一个循环,并以某种方式来注意当你等待了太久。 –
谢谢我会尝试 – user3770009