Skip to content

Instantly share code, notes, and snippets.

@antonioastorino
Last active July 8, 2025 09:27
Show Gist options
  • Select an option

  • Save antonioastorino/2416420f1905c9b74a2d64429e1e58b3 to your computer and use it in GitHub Desktop.

Select an option

Save antonioastorino/2416420f1905c9b74a2d64429e1e58b3 to your computer and use it in GitHub Desktop.
Using `flock()` in C
/*
# flock in C
## Motivation
Try and search for "Flock in C" on YouTube. You won't find this stuff.
## Explanation
This tiny project is to show how to use a file to share data between 2 processes. For simplicity, a producer and a consumer are created within the same executable.
The producer uses `flock` with the "exclusive" flag. That is because the producer wants nobody else to access the file while it is being written. Also, the producer prefers to wait for readers to complete reading. Hence, the producer blocks until the readings are in progress.
The consumer uses the "shared" flag. In fact, while the shared file is being written, other processes are allowed to read it but the producer(s) should not access it for writing. Also, the consumer doesn't want to get stuck if the file is locked. Therefore, the consumer uses the "non-block" flag.
## Resources
- [TutorialsPoint](https://www.tutorialspoint.com/unix_commands/flock.htm)
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <string.h>
#include <errno.h>
#include <sys/wait.h>
// #define LOCK_SH 1 /* shared lock */
// #define LOCK_EX 2 /* exclusive lock */
// #define LOCK_NB 4 /* don't block when locking */
// #define LOCK_UN 8 /* unlock */
#define FILE_NAME "tmp.txt"
int main(void)
{
int pid = fork();
if (pid)
{
int fd = open(FILE_NAME, O_WRONLY | O_CREAT, 0666);
for (int i = 0; i < 20; i++)
{
printf("[PRODUCER] locking with blocking\n");
flock(fd, LOCK_EX);
printf("[PRODUCER] \e[31mlocked\e[0m - pretend writing\n");
sleep(1);
flock(fd, LOCK_UN);
printf("[PRODUCER] \e[32munlocked\e[0m\n");
sleep(1);
}
}
else
{
int fd = open(FILE_NAME, O_RDONLY);
for (int i = 0; i < 20;)
{
printf("\t\t[CONSUMER] try locking\n");
if (flock(fd, LOCK_SH | LOCK_NB) == -1 && errno == EWOULDBLOCK)
{
printf("\t\t[CONSUMER] file not ready\n");
usleep(500000);
}
else
{
i++;
printf("\t\t[CONSUMER] \e[31mlocked\e[0m - pretend reading\n");
sleep(1);
flock(fd, LOCK_UN);
printf("\t\t[CONSUMER] \e[32munlocked\e[0m\n");
usleep(10000);
}
}
wait(NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment