我目前正在尝试实现并发服务器(即通过分支新的子进程来处理多个进程)。
每个客户端执行读/写请求以从位于服务器中的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!");
}
如果我的方向正确,有人可以指导我吗?
答案 0 :(得分:0)
也许。您必须添加错误处理(因此您在锁定失败时会注意到),等待(锁定失败时)和超时(当另一个孩子被卡住并且永远不会释放锁定时)。
但根据我的经验,这个过程很脆弱。改为创建一个套接字。让孩子们连接到插座。然后使用主进程将命令提供给子进程。在此方案中,主进程替换单个文件。
这有几个好处: