Skip to content

Instantly share code, notes, and snippets.

@ipartola

ipartola/main.c Secret

Created September 15, 2015 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipartola/2b7d6ecc3e6c0fbdb668 to your computer and use it in GitHub Desktop.
Save ipartola/2b7d6ecc3e6c0fbdb668 to your computer and use it in GitHub Desktop.
fcntl file locking test
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
int var_glb; /* A global variable*/
int main(int argc, char **argv){
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
FILE *fp;
int fd;
fp = fopen("/tmp/test.dest", "a+");
fd = fileno(fp);
printf("opened by %d. About to lock.\n", getpid());
if (fcntl(fd, F_SETLKW, &fl) < 0){
printf("fcntl twidgie failed \n");
}
else{
printf("Locked by %d\n", getpid());
}
fprintf(fp, "These are the times that try men's soils.\n");
fprintf(fp, "Why do the barnicles seeth in the deep?\n");
fprintf(fp, "Maybe the stolid twidgies lurk until this day?\n\n\n");
printf("%d is going to sleep\n", getpid());
sleep(10);
fl.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &fl) < 0){
printf("fcntl (unlock) twidgie failed\n");
}
else{
printf("UnLocked by %d\n", getpid());
}
fclose(fp);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment