Re: g_rename() problem on Windows (and suggested remedy)




On 25 Mar 2012, at 10:20, John Emmas wrote:


'g_rename()' only works properly (in the Windows version) if there are no open handles to the file being renamed.  On Linux, I think a file can be renamed at any time - even if some process already has it open.   A handle is a handle and shouldn't care about what the file is actually called.

AFAICT the problem on Windows is caused by the fact that g_open() uses _wopen() for opening the file.  Perhaps a better choice would have been CreateFile() because it allows files to be opened with permission for "shared deletion and shared renaming".  This would in theory allow g_rename() to work the same on Windows as on Linux.


This morning I looked into this a bit deeper but I soon realised that the handle returned by g_creat() (for example) is expected to be used by read() / write() / seek() / close() etc.  There are no Glib equivalents for those functions AFAICT (no g_read() / no g_seek(), g_close() or whatever).  On the face of it, this would negate my idea of using CreateFile() since its handles aren't compatible with read() / write() / seek() etc.   In case anyone's interested though, I think I've found a simple fix.  Here's the basic principle for creating a readable / writable file:-

HANDLE hFile = CreateFile(FNAME, GENERIC_WRITE, 
                             FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
                             NULL, CREATE_ALWAYS, NULL, NULL);

if (INVALID_HANDLE_VALUE == hFile)
return -1;
else
return (_open_osfhandle((long)hFile, _O_RDWR));

The above code gives me a handle which is functionally equivalent to a Glib file handle (it can be used with read() and write() etc) BUT the file can be renamed - even when open.  This makes the Windows version work more like its Linux counterpart and g_rename() should work similarly on both platforms.  Of course it's slightly more complex than I've described and I'd need to modify other functions as well as g_creat().  g_open() and g_fopen() are the most obvious ones.  Not sure what would happen with g_freopen() but I can look into it.

If there's anyone still developing Glib for Windows, please let me know if you want me to provide a patch once I'm sure it works.

John


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]