#include <stdio.h>
#include <sys/file.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

extern int errno;

int main (int argc, char **argv) {

  int fd, file, result;
  struct flock locks;

  if (argc < 2) {
    printf ("%s <filename, filename, ....>\n", argv[0]);
    return (1);
  }

  for (file=1; file<argc; file++) {
    if (fd = open (argv[file], O_RDONLY) == -1) {
      printf ("%s : Unable to open (%s)\n", argv[file], strerror(errno));
    }

    if (lseek (fd, 0, SEEK_SET) != 0) {
      printf ("%s : Unable to lseek to beginning (%s)\n", argv[file], strerror(errno));
    }

    locks.l_type = F_WRLCK;
    locks.l_whence = SEEK_SET;
    locks.l_start = 0;
    locks.l_len = 0;
    locks.l_pid = 0;

    result = fcntl (fd, F_GETLK, &locks);

    if (result == -1) {
      printf ("%s : Unable to lock file (%s) [lock possibly held by %d ??]\n",
	      argv[file], strerror(errno), locks.l_pid);
    }
    else {
      printf ("%s : Locking went just fine.\n", argv[file]);
      locks.l_type = F_UNLCK;
      locks.l_pid = 0;
      if (fcntl (fd, F_SETLK, &locks) == -1) {
	printf ("**** %s : Unable to unlock (%s) [wierd]\n", argv[file],
		strerror(errno));
      }
    }

    close (fd);
  }

  return 0;
}
   

	    
