-------* Start of Code *----------
/* lock-file.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int
main (int argc, char *argv[])
{
  struct flock lock_info;
  int fd_no;

  fd_no = open ("a.out", O_RDWR);
  if (fd_no == -1)
    {
      perror ("open ()");
      exit (1);
    }

  while (1)
    {
      if (-1 == fcntl (fd_no, F_GETLK, &lock_info))  /* get lock info */
        {
          perror ("fcntl()");
          exit (1);
        }
      printf ("Lock stat of %s : %d \n", lock_info.l_type);
      if (lock_info.l_type != F_UNLCK) sleep (1); /* if file is locked then sleep */
      else
        {
          lock_info.l_type = F_RDLCK; /* lock for reading */
          lock_info.l_whence = SEEK_SET;
          lock_info.l_start = 0l;
          lock_info.l_len = 0;
          fcntl (fd_no, F_SETLK, &lock_info);
          break;
        }
    }

  printf (" %s file locked ...\n", argv[0]);
  printf (" I'm going to sleep. \n");
  printf (" Press Ctrl-C to unlock! \n");
  while (1) sleep (5);

  return 0;
}

---* End of code *------

I compiled with
gcc -o lock-file lock-file.c
There was no error and current directory contain a.out file.

I run this program. But end with printing following message.
fcntl(): Invalid argument

What is the wrong?



Reply via email to