Skip to content

Instantly share code, notes, and snippets.

@simonjbeaumont
Last active October 14, 2022 08:33
Show Gist options
  • Save simonjbeaumont/7bd12f1f97e162734b6fec847d3a969f to your computer and use it in GitHub Desktop.
Save simonjbeaumont/7bd12f1f97e162734b6fec847d3a969f to your computer and use it in GitHub Desktop.
flock-playground
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
#include <sys/file.h>
#include <unistd.h>
enum new_fd_method_t {
flock_test_open,
flock_test_dup,
};
int main() {
const char *new_fd_method_env_key = "NEW_FD_METHOD";
const char *path = "./mylock";
enum new_fd_method_t new_fd_method;
int fd, new_fd;
const char *new_fd_method_env_val = getenv(new_fd_method_env_key);
if (new_fd_method_env_val == NULL) {
fprintf(stderr, "usage: Run with NEW_FD_METHOD set to `open` or `dup`\n");
exit(EXIT_FAILURE);
} else if (strcmp(new_fd_method_env_val, "open") == 0) {
new_fd_method = flock_test_open;
} else if (strcmp(new_fd_method_env_val, "dup") == 0) {
new_fd_method = flock_test_dup;
} else {
fprintf(stderr, "usage: Run with NEW_FD_METHOD set to `open` or `dup`\n");
exit(EXIT_FAILURE);
}
if ((fd = open(path, O_CREAT | O_TRUNC | O_RDWR)) < 0) {
fprintf(stderr, "error creating lock file %s: %s\n", path, strerror(errno));
exit(errno);
}
if ((flock(fd, LOCK_NB | LOCK_SH)) < 0) {
fprintf(stderr, "error getting shared lock using fd %d: %s\n", fd, strerror(errno));
exit(errno);
}
if ((flock(fd, LOCK_NB | LOCK_EX)) < 0) {
fprintf(stderr, "error upgrading shared lock to exclusive lock using fd %d: %s\n", fd, strerror(errno));
exit(errno);
}
if ((flock(fd, LOCK_UN)) < 0) {
fprintf(stderr, "error unlockind lock using fd %d: %s\n", fd, strerror(errno));
exit(errno);
}
if ((flock(fd, LOCK_NB | LOCK_SH)) < 0) {
fprintf(stderr, "error reaquiring shared lock with original fd %d: %s\n", fd, strerror(errno));
exit(errno);
}
switch (new_fd_method) {
case flock_test_open:
if ((new_fd = open(path, O_RDWR)) < 0) {
fprintf(stderr, "error opening same lock file with new fd: %s\n", strerror(errno));
exit(errno);
}
break;
case flock_test_dup:
if ((new_fd = dup(fd)) < 0) {
fprintf(stderr, "error duplicating fd: %s\n", strerror(errno));
exit(errno);
}
break;
}
if ((flock(new_fd, LOCK_NB | LOCK_EX)) < 0) {
fprintf(stderr, "error obtaining exclusive lock with new fd %d: %s\n", new_fd, strerror(errno));
exit(errno);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment