使用fnctl()锁定和解锁文件以进行读写(多个进程)

时间:2014-06-24 12:18:24

标签: c linux client-server

我目前正在尝试实现并发服务器(即通过分支新的子进程来处理多个进程)。

每个客户端执行读/写请求以从位于服务器中的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!");
}

如果我的方向正确,有人可以指导我吗?

1 个答案:

答案 0 :(得分:0)

也许。您必须添加错误处理(因此您在锁定失败时会注意到),等待(锁定失败时)和超时(当另一个孩子被卡住并且永远不会释放锁定时)。

但根据我的经验,这个过程很脆弱。改为创建一个套接字。让孩子们连接到插座。然后使用主进程将命令提供给子进程。在此方案中,主进程替换单个文件。

这有几个好处:

  • 主进程会保留子项状态(他们正在处理的内容)的标签,您可以编写工具来查看此统计信息。稍后,您可以将其用于健康监控。
  • 您不需要使用套接字锁定。
相关问题