OpenVMS Source-Code Demos
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 OpenVMS CRTL libraries published by
// HP in 2005 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 allow you to type: "errno 9" or "error -l"
// history:
// 20211113 NSR 1. original effort (just fooling around; works on CentOS-7)
// =================================================================================
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h> // for the strict use of flock
#define __NEW_STARLET 1 // enable 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; // this 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);
}
Back to OpenVMS
Back to OpenVMS
Demo Index
Back to Home
Neil Rieck
Waterloo, Ontario, Canada.