Question

I m working with File Locking in interprocess Communication , the following code bugs me... when run through terminal in Macintosh

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <unistd.h>

  int main(int argc , char *argv[])
  {
   // l_type , l_whence , l_start , l_len , l_pid
    struct flock f1 = {F_WRLCK , SEEK_SET , 0 , 0 , 0};
    int fd;

  f1.l_pid = getpid() ;

// if command line arguments  , then assign a Read Lock
if (argc > 1)
{
    f1.l_type = F_RDLCK ;
}

if ((fd = open("lockdemo.c", O_RDWR)) == -1)
{
    perror("open");
    exit(1);
}

printf("Press <RETURN> to try to get lock");
getchar() ;

printf("trying to get lock...");

if (fcntl(fd, F_SETLKW , &f1)  == -1)
{
    perror("fcntl");
    exit(1);
}


printf("got lock !\n");
printf("Press <RETURN> to release lock:");
getchar();

f1.l_type = F_UNLCK ; //set to unlock same region

if (fcntl(fd, F_SETLK , &f1) == -1)
{
    perror("fcntl");
    exit(1);
}

printf("Unlocked .. \n");
close(fd);

return 0;
 }

But the following error appears : fnctl : invalid argument

plz help me in this question...

Was it helpful?

Solution

On MacOs, the members of struct flock have a different order than in Linux.

to make your code portable you should assign the fields by name, and not assume a particular order.

From the MacOS Man page for fcntl:

         struct flock {
             off_t       l_start;    /* starting offset */
             off_t       l_len;      /* len = 0 means until end of file */
             pid_t       l_pid;      /* lock owner */
             short       l_type;     /* lock type: read/write, etc. */
             short       l_whence;   /* type of l_start */
         };

OTHER TIPS

I tried your code and it works fine without any modification on Linux Min 12 64 bit.

 gcc lock.c 
-Compaq-6200-Pro-MT-PC ~/Dropbox/Misc $ ./a.out 1
Press <RETURN> to try to get lock
trying to get lock...got lock !
Press <RETURN> to release lock:
Unlocked .. 
-Compaq-6200-Pro-MT-PC ~/Dropbox/Misc $ ./a.out
Press <RETURN> to try to get lock
trying to get lock...got lock !
Press <RETURN> to release lock:
Unlocked .. 

Of course i created a lockdemo.c file in the same folder.

Seems like your locking api on mac might have issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top