File locking

Chris Blake
Mon Jan 21 20:33:00 GMT 2002

How does one do Posix file locking with gcc3 / libstdc++-v3?
I posted this question to gcc-help last week, but it seems that
nobody knows the answer. I realise the C++ standard may not concern
itself with such OS-specific things as file locking, but I'd appreciate
any suggestions, even if the only solution is to reinstall g++ 2.95.

I'm trying to compile a program with g++ 3.0.2 under Solaris 8.
It is a simple booking system where the program locks a booking data
file, reads the last request number from it, then writes a new booking
with an incremented request number before releasing the lock. 

The following fragment used to compile under g++ 2.95...

#define GCC3  1

#if GCC3              // mods for gcc 3
#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <cstdio>
#include <cctype>
using namespace std;
#include <fstream.h>
#include <fcntl.h>                      // for file locking
#include <stdio.h>
#include <ctype.h>

int JobRequest::getlock()
        struct flock    lock;

    fd = jobfile.rdbuf()->fd();
    lock.l_type = F_WRLCK;
    lock.l_start = 0;
    lock.l_whence = SEEK_SET;
    lock.l_len = 0;

    return( fcntl(fd, F_SETLK, &lock) );

....but with g++ 3.0.2 I get
request.cpp: In member function `int JobRequest::getlock()':
request.cpp:70: no matching function for call to `std::basic_filebuf<char, 
   std::char_traits<char> >::fd()'

I've also tried replacing the body of the function with the line

  return( fcntl(fd, F_SETLKW, file_lock(F_WRLCK, SEEK_SET)));

but g++  then gives the error...
  request.cpp:79: `file_lock' undeclared (first use this function)

...and file_lock() does not appear to be defined in any of the system
include files.


Chris Blake

More information about the Libstdc++ mailing list