我目前正在尝试实现一个并发服务器(即通过分叉新的子进程来处理多个进程)。
每个客户端执行读/写请求来读取位于服务器中的file.txt文件。我目前使用fnctl()
来处理同步,即。我可以有多个读,但只有一个写。
这是我到目前为止所做的示例代码:
{
FILE *file = fopen("file.txt", "w+");
fd = fileno(file);
printf("nThis is the file descriptor : %dn", 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!");
}
如果我走对了方向,有人能给我指路吗? 也许吧。您必须添加错误处理(当锁定失败时您会注意到),等待(当锁定失败时)和超时(当另一个子线程卡住并且锁从未释放时)。
但根据我的经验,这个过程是脆弱的。而是创建一个套接字。让孩子们连接到插座上。然后使用主进程向子进程提供命令。在此场景中,主进程将替换单个文件。
这有两个优点:
- 主进程保持子进程状态的标签(它们正在做什么),您可以编写一个工具来查看这些统计信息。稍后,您可以将其用于运行状况监视。
- socket不需要锁。