flock_demo.c

// ======================================================================== // title : flock_demo.c // author : Neil Rieck // created: 2021-11-13 // notes :
// 1) 'lockf' is published in the POSIX libraries // 2) 'flock' is published in the BSD/Linux libraries // 3) 'flock' and 'lockf' are not found in the CRTL libraries published
// by HP for OpenVMS in 2005 (hopefully VSI can fix this) so you might
// need to rely upon the ANSI function "void flockfile()" -OR- call
// routines specifically written for the VMS "distributed lock manager" // Linux : "yum install moreutils" will enables commands like:
// "errno 9" or "error -l" // history: // 20211113 NSR 1. original effort (this works on CentOS-7) // ======================================================================== #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <sys/file.h> // for strict use of flock #define __NEW_STARLET 1 // strict starlet (>= VMS7) // #define TESTFILENAME "flock_demo.dat" // #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 extern int errno; // is located elsewhere // void debug(int rc){ if ((rc>0)||(errno>0)){ printf("rc: %d err: %d\n", rc, errno); errno = 0; } } // void main(){ FILE *fp; char *tmp; int rc; int seq; // ========================================= printf("fopen\n"); fp = fopen(TESTFILENAME,"r+"); // open for read-write if (fp == NULL){ // oops, handle first time printf("err: %d\n", errno); errno = 0; printf("fopen2\n"); fp = fopen(TESTFILENAME,"w+"); // create the file if (fp != NULL){ seq = 1; // init fputc(seq, fp); // write fseek(fp, 0L, SEEK_SET); // rewind } } if (fp == NULL){ printf("err: %d\n", errno); perror("-e-cannot open file"); exit(2); } printf("flock\n"); rc = flock( fileno(fp), LOCK_EX ); debug(rc); printf("now run this program on another session\n"); printf("then hit <enter> to continue"); getchar(); printf("\n"); printf("funlock\n"); rc = flock( fileno(fp), LOCK_UN ); debug(rc); printf("fclose\n"); rc = fclose(fp); debug(rc); }

left hand Back to Linux Demo Index
home Back to Home
Neil Rieck
Waterloo, Ontario, Canada.