/* * testlock - test if a fle has been flocked * * usage: * testlock filename * * filename file to check if it is locked * * Exits with 0 if not locked (or file missing or not readable), 1 if locked. * * NOTE: In order to test locking, this must try to form a shared lock. * To be effective, the real locking process must obtain an exclusive * lock to deny this test. */ /* * * Copyright (C) 1997 Landon Curt Noll, all rights reserved. * * Permission to use, copy, modify, and distribute this software and * its documentation for any purpose is hereby granted, provided that * the above copyright, this permission notice, and the disclaimer * below appear in all of the following: * * * supporting documentation * * source copies * * source works derived from this source * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * * Landon Curt Noll /\oo/\ * * chongo@{toad,sgi}.com Share and Enjoy! */ #include #include #include #include #include #include main(int argc, char *argv[]) { int fd; /* open file descriptor */ char *filename; /* filename to test */ /* * parse args */ if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); exit(0); } filename = argv[1]; /* * open the file for reading */ fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "%s: cannot open %s of reading\n", argv[0], filename); exit(0); } /* * check file for locking */ errno = 0; if (flock(fd, LOCK_SH|LOCK_NB) < 0) { if (errno == EWOULDBLOCK) { /* file was locked */ exit(1); } else { fprintf(stderr, "%s: bad lock of %s\n", argv[0], filename); exit(0); } } /* * file was not locked but now is share locked ... until ... */ /* close and unlock */ close(fd); /* report that it was not locked */ exit(0); }