fcntl works in linux but not in mac os x

Hi,

Unless I am missing some serious differences in Mac and linux in terms of C programming, I dont know why this would happen. Please take a look at the following piece of code fragment:

bool add_input_to_db(Cons *new_data) {
  // Set the attributes of the lock 	
  struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0};	 
  int fd = open(LOGFILE, O_APPEND | O_SYNC | O_CREAT | O_WRONLY, 0600);
  if (fd == -1) {
    perror(LOGFILE);
    return false;
  }
  // Get our PID
  fl.l_pid = getpid();
  // Return false on error
  if (fcntl(fd, F_SETLKW, &fl) < 0){
     perror("fcntl");
     return false;
  }
  FILE *database = fdopen(fd, "a");
  int result = write_questions(new_data, database, false);
  // Set to unlock before closing the file
  fl.l_type = F_UNLCK;
  if (fcntl(fd, F_SETLK, &fl) < 0){
     perror("fcntl");
     return false;
  }
  fclose(database);
  return (bool) result;
}

This function is part of a bigger programs that takes in user input and logs it into a file. As you might see, I am trying to get an write lock on the logfile as soon as it opens and release the lock before the file is closed. When I run it on linux (ubuntu hardy), the program runs without any problems. However, when I run it on my mac (Leopard), I get:

fcntl: Invalid argument

If someone could explain why this would be, it'd be helpful.

Thanks.

I'd suggest assigning members of fl instead of giving fl a definition block. It's possible the layout of a flock structure has members before the standard ones on osx.

Hi,

You were right. I did not notice it earlier, but when I checked the manpage for fcntl, the struct members were in different order in mac than in linux.

I wonder why they would do that though..
Thanks.

POSIX standards specify what has to be in a struct, the standards do not restrict additional struct members.

From POSIX on struct fl:

The structure flock describes a file lock. It shall include the following members:

short  l_type   Type of lock; F_RDLCK, F_WRLCK, F_UNLCK. 
short  l_whence Flag for starting offset. 
off_t  l_start  Relative offset in bytes. 
off_t  l_len    Size; if 0 then until EOF. 
pid_t  l_pid    Process ID of the process holding the lock; returned with F_GETLK. 

The mode_t, off_t, and pid_t types shall be defined as described in <sys/types.h>.