Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect handling of lock modification by FLOCK. #185

Open
kpan2034 opened this issue Jul 15, 2023 · 0 comments
Open

Incorrect handling of lock modification by FLOCK. #185

kpan2034 opened this issue Jul 15, 2023 · 0 comments
Assignees

Comments

@kpan2034
Copy link
Contributor

According to the flock man page (https://linux.die.net/man/2/flock):

A process may only hold one type of lock (shared or exclusive) on a file. Subsequent flock() calls on an already locked file will convert an existing lock to the new lock mode.

This results in the following expected behavior:

  • When a process that has a shared lock calls flock again to acquire an exclusive lock, it is able to upgrade the lock to an exclusive lock.
  • When a process that has an exclusive lock calls flock again to acquire a shared lock, it is able to downgrade it to a shared lock as well

The Lind implementation of flock differs here: instead of modifying the lock, it waits to be able to acquire it.
You can see this difference in behavior by running the following program.

#undef _GNU_SOURCE
#define _GNU_SOURCE

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

#define FILE "test.txt"

int main(int argc, char **argv) {
  // Create a file to use
  int fd = open(FILE, O_RDWR | O_CREAT, 0777);
  if (fd == -1) {
    perror("OPEN FAILED\n");
    exit(EXIT_FAILURE);
  }

  int lock;

  // Obtain a shared lock on the file
  lock = flock(fd, LOCK_SH);
  if (lock == -1) {
    perror("LOCK FAILED\n");
    exit(EXIT_FAILURE);
  }

  // Upgrade the lock to an exclusive lock
  lock = flock(fd, LOCK_EX);
  if (lock == -1) {
    perror("LOCK FAILED\n");
    exit(EXIT_FAILURE);
  }

  // Release the lock
  lock = flock(fd, LOCK_UN);
  if (lock == -1) {
    perror("LOCK FAILED\n");
    exit(EXIT_FAILURE);
  }

  printf("OK\n");
  fflush(stdout);

  // Close file before removing
  close(fd);
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants