#include #include #include #include #include #include #include #include #include #include #include #include #define failf(name) do { fprintf(stderr,"%s: ",pname); perror(name"()"); exit(EXIT_FAILURE); } while (0) const char version[]="This is FLock, version 1.0\n"; int verbose; char *pname; static void usage(void) __attribute__((noreturn)); static void usage(void) { fprintf(stderr,"\ %s\ This command acts as an interface to flock(2):\n\ \n\ Usage: flock [{-s|--shared}|{-x|--exclusive}] [-n|--nonblock]\n\ [-v|--verbose] [-h|--help] [-V|--version]\n\ \n\ \n\ -s, --shared\tCreate shared lock (LOCK_SH) - DEFAULT\n\ -x, --exclusive\tCreate exclusive lock (LOCK_EX)\n\ -n, --nonblock\tFail immediately if req. lock is busy\n\ -v, --verbose\tDisplay progress during locking\n\ -h, --help\tPrint a summary of the options\n\ -V, --version\tPrint the version number\n\ ",version); exit(EXIT_FAILURE); } const struct option longopts[]={ {"shared" ,0,0,'s'}, {"exclusive",0,0,'x'}, {"nonblock" ,0,0,'n'}, {"verbose" ,0,0,'v'}, {"help" ,0,0,'h'}, {"version" ,0,0,'V'}, {NULL ,0,0,0 }}; int main(int argc,char **argv) { char *fn,*cmd; int locktype=LOCK_SH,nonblock=0,fd,optc; pname=*argv; while ((optc=getopt_long(argc,argv,"sxnvhV",longopts,NULL))!=EOF) switch (optc) { case 's': locktype=LOCK_SH; break; case 'x': locktype=LOCK_EX; break; case 'n': nonblock=LOCK_NB; break; case 'v': verbose=1; break; case 'V': fprintf(stderr,version); exit(EXIT_FAILURE); default: /* also 'h' */ usage(); break; } if (optind+2!=argc) { fprintf(stderr,"%s: Incorrect number of parameters (command needs quoting?)!\n",pname); exit(EXIT_FAILURE); } fn=argv[optind]; cmd=argv[optind+1]; if (verbose) { fprintf(stderr,"%s: Opening \"%s\"...",pname,fn); fflush(stderr); } if ((fd=open(fn,O_RDONLY|(nonblock?O_NONBLOCK:0)))==-1) failf("open"); if (verbose) { fprintf(stderr,"done\n%s: Locking \"%s\"...",pname,fn); fflush(stderr); } if (flock(fd,locktype|nonblock)) failf("flock"); if (verbose) { fprintf(stderr,"done\n%s: Running \"%s\"...",pname,cmd); fflush(stderr); } if (system(cmd)==-1) failf("system"); if (verbose) { fprintf(stderr,"done\n%s: Finishing - removing lock.\n",pname); } return(EXIT_SUCCESS); }