Ejemplo n.º 1
0
static NTSTATUS DOKAN_CALLBACK
MirrorUnlockFile(LPCWSTR FileName, LONGLONG ByteOffset, LONGLONG Length,
                 PDOKAN_FILE_INFO DokanFileInfo) {
  WCHAR filePath[MAX_PATH];
  HANDLE handle;
  LARGE_INTEGER length;
  LARGE_INTEGER offset;

  GetFilePath(filePath, MAX_PATH, FileName);

  DbgPrint(L"UnlockFile %s\n", filePath);

  handle = (HANDLE)DokanFileInfo->Context;
  if (!handle || handle == INVALID_HANDLE_VALUE) {
    DbgPrint(L"\tinvalid handle\n\n");
    return STATUS_INVALID_HANDLE;
  }

  length.QuadPart = Length;
  offset.QuadPart = ByteOffset;

  if (!UnlockFile(handle, offset.HighPart, offset.LowPart, length.HighPart,
                  length.LowPart)) {
    DWORD error = GetLastError();
    DbgPrint(L"\terror code = %d\n\n", error);
    return ToNtStatus(error);
  }

  DbgPrint(L"\tsuccess\n\n");
  return STATUS_SUCCESS;
}
Ejemplo n.º 2
0
// выводит строку типа "DD.MM.YYYY HH:MM:SS text"
void SysLog(const wchar_t *fmt, ...)
{
  const static wchar_t SYSLOGENABLED[]=L"SYSLOGENABLED";
  static wchar_t temp[4096];

  static SYSTEMTIME st;
  GetLocalTime(&st);
  wsprintf(temp, L"%02d.%02d.%04d %02d:%02d:%02d ",
           st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute, st.wSecond);
  static wchar_t *msg=temp+lstrlen(temp);

  va_list argptr;
  va_start(argptr, fmt);
  wvsprintf(msg, fmt, argptr);
  va_end(argptr);

  lstrcat(msg, L"\r\n");
  HANDLE f =
    CreateFile(SysLogName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS,
               FILE_ATTRIBUTE_NORMAL, NULL);

  if (f != INVALID_HANDLE_VALUE)
    {
      DWORD dwBytesToWrite = lstrlen(temp)*sizeof(wchar_t), dwBytesWritten = 0;
      DWORD dwPos = SetFilePointer(f, 0, NULL, FILE_END);

      LockFile(f, dwPos, 0, dwPos + dwBytesToWrite, 0);
      WriteFile(f, temp, dwBytesToWrite, &dwBytesWritten, NULL);
      UnlockFile(f, dwPos, 0, dwPos + dwBytesToWrite, 0);
    }
  CloseHandle(f);
}
Ejemplo n.º 3
0
void unlockFile() {

  if (hAppend) { return ; }

  UnlockFile(hAppend, 0, 0, 0, 0);
  CloseHandle(hAppend);
}
Ejemplo n.º 4
0
static int
alock_release_lock ( int fd, int slot )
{
	int res;
	
#if defined( HAVE_LOCKF )
	res = lseek (fd, (off_t) (ALOCK_SLOT_SIZE * slot), SEEK_SET);
	if (res == -1) return -1;
	res = lockf (fd, F_ULOCK, (off_t) ALOCK_SLOT_SIZE);
	if (res == -1) return -1;
#elif defined ( HAVE_FCNTL )
	struct flock lock_info;
	(void) memset ((void *) &lock_info, 0, sizeof (struct flock));

	lock_info.l_type = F_UNLCK;
	lock_info.l_whence = SEEK_SET;
	lock_info.l_start = (off_t) (ALOCK_SLOT_SIZE * slot);
	lock_info.l_len = (off_t) ALOCK_SLOT_SIZE;

	res = fcntl (fd, F_SETLKW, &lock_info);
	if (res == -1) return -1;
#elif defined( _WIN32 )
	HANDLE hh = _get_osfhandle ( fd );
	if ( !UnlockFile ( hh, ALOCK_SLOT_SIZE*slot, 0,
		ALOCK_SLOT_SIZE, 0 ))
		return -1;
#else
#   error alock needs lockf, fcntl, or LockFile[Ex]
#endif

	return 0;
}
Ejemplo n.º 5
0
static int DOKAN_CALLBACK
MirrorUnlockFile(
	LPCWSTR				FileName,
	LONGLONG			ByteOffset,
	LONGLONG			Length,
	PDOKAN_FILE_INFO	DokanFileInfo)
{
	WCHAR	filePath[MAX_PATH];
	HANDLE	handle;
	LARGE_INTEGER	length;
	LARGE_INTEGER	offset;

	GetFilePath(filePath, MAX_PATH, FileName);

	DbgPrint(L"UnlockFile %s\n", filePath);

	handle = (HANDLE)DokanFileInfo->Context;
	if (!handle || handle == INVALID_HANDLE_VALUE) {
		DbgPrint(L"\tinvalid handle\n\n");
		return -1;
	}

	length.QuadPart = Length;
	offset.QuadPart = ByteOffset;

	if (UnlockFile(handle, offset.HighPart, offset.LowPart, length.HighPart, length.LowPart)) {
		DbgPrint(L"\tsuccess\n\n");
		return 0;
	} else {
		DbgPrint(L"\tfail\n\n");
		return -1;
	}
}
Ejemplo n.º 6
0
    int logger(char *procName,DWORD pid,DWORD tid,char *type,LPVOID *desc) {
        HANDLE logfile;
        char logname[20];
        char logbuffer[BUFFSIZE];
        DWORD position, bytesWritten;
        SYSTEMTIME time;
        char inst[20];

        sprintf_s(logname,sizeof(logname),"%s.log",procName);
        GetLocalTime(&time);
        sprintf(inst,"%02d:%02d:%02d.%03d", time.wHour,time.wMinute,time.wSecond,time.wMilliseconds);
        sprintf(logbuffer,"[%s Proc:%s PID:%d TID:%d Type:%s] %s\n",inst,procName,pid,tid,type,desc);
        
        logfile = CreateFileA(logname,
            FILE_APPEND_DATA,
            FILE_SHARE_READ,
            NULL,
            OPEN_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        if (logfile == INVALID_HANDLE_VALUE) {
            printf("No se pudo crear or abrir el log.\n");
        } else {
            printf("Escribiendo log...\n");
            position = SetFilePointer(logfile, 0, NULL, FILE_END);
            LockFile(logfile, position, 0, strlen(logbuffer), 0);
            WriteFile(logfile, logbuffer, strlen(logbuffer), &bytesWritten, NULL);
            UnlockFile(logfile, position, 0, strlen(logbuffer), 0);
        }
        
        CloseHandle(logfile);
        return EXIT_SUCCESS;
    }
Ejemplo n.º 7
0
int __ll_unlock(int handle, int offset, int length)
{
   if (UnlockFile((HANDLE)handle,offset,0,length,0))
      return 0 ;
   errno = GetLastError() ;
   return -1 ;
}
Ejemplo n.º 8
0
    void writeLogString(char * procName , char * logString) {
        HANDLE logfile;
        char logname[30];
        DWORD position, bytesWritten;
        
		ZeroMemory(logname , 30);
		sprintf_s(logname , sizeof(logname) , "../logs/%s.log" , procName);
                    
        logfile = CreateFileA(logname,
            FILE_APPEND_DATA,
            FILE_SHARE_READ,
            NULL,
            OPEN_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        if (logfile == INVALID_HANDLE_VALUE) {
            printf("[IO] No se pudo crear or abrir el log.\n");
        } else {
            position = SetFilePointer(logfile, 0 , NULL , FILE_END);
            LockFile(logfile, position , 0 , (DWORD) strlen(logString) , 0);
            WriteFile(logfile, logString , (DWORD) strlen(logString) , &bytesWritten , NULL);
            UnlockFile(logfile , position , 0 , (DWORD) strlen(logString) , 0);
        }
        
        CloseHandle(logfile);
    }
Ejemplo n.º 9
0
int tup_unflock(tup_lock_t fd)
{
	if(UnlockFile(fd, 0, 0, 1, 0) == 0) {
		errno = EIO;
		return -1;
	}
	return 0;
}
Ejemplo n.º 10
0
_WCRTLINK int unlock( int hid, unsigned long offset, unsigned long nbytes )
{
    __handle_check( hid, -1 );

    if( !UnlockFile( __getOSHandle( hid ), offset, 0L, nbytes, 0L ) ) {
        return( __set_errno_nt() );
    }
    return( 0 );
}
Ejemplo n.º 11
0
void unlock_fd(int fd)
{
    HANDLE hFile;
    if (fd == -1)
	return;

    hFile = (HANDLE)_get_osfhandle(fd);
    
    UnlockFile(hFile, 0, 0, 64, 0);
}
Ejemplo n.º 12
0
BOOL FileLockThread::ReleaseFileLock()
{
	for (auto it = fileHandles.begin(); it != fileHandles.end(); it++)
	{
		if (UnlockFile(*it, 0, 0, GetFileSize(*it, 0), 0) != 0)
			::CloseHandle(*it);
	}
	fileHandles.clear();
	return TRUE;
}
Ejemplo n.º 13
0
APIRET os2APIENTRY DosSetFileLocks(os2HFILE hFile,
                                   PFILELOCK pflUnlock,
                                   PFILELOCK pflLock,
                                   ULONG /*timeout*/,
                                   ULONG flags)
{
        APIRET rc;
        int idx=(int)hFile;
        FileTable.lock(idx);
        if(FileTable[idx]) {
                rc=0;
                if(pflLock) {
                        OVERLAPPED o;
                        memset(&o,0,sizeof(o));
                        o.Offset = pflLock->lOffset;
                        o.OffsetHigh = 0;
                        if(!LockFileEx(FileTable[idx]->ntFileHandle,
                                       flags&1?0:LOCKFILE_EXCLUSIVE_LOCK,
                                       0,
                                       pflLock->lRange, 0,
                                       0
                                    )) {
                                rc = (APIRET)GetLastError();
                        }
                }
                if(rc==0 && pflUnlock) {
                        if(!UnlockFile(FileTable[idx]->ntFileHandle,
                                       pflUnlock->lOffset, 0,
                                       pflUnlock->lRange, 0
                                    )) {
                                UnlockFile(FileTable[idx]->ntFileHandle,
                                           pflLock->lOffset,0,
                                           pflLock->lRange,0
                                          );
                                rc = (APIRET)GetLastError();
                        }
                }
        } else
                rc = 6; //invalid handle
        FileTable.unlock(idx);
        return rc;
}
Ejemplo n.º 14
0
RTR3DECL(int)  RTFileUnlock(RTFILE hFile, int64_t offLock, uint64_t cbLock)
{
    Assert(offLock >= 0);

    if (UnlockFile((HANDLE)RTFileToNative(hFile),
                   LOW_DWORD(offLock), HIGH_DWORD(offLock),
                   LOW_DWORD(cbLock), HIGH_DWORD(cbLock)))
        return VINF_SUCCESS;

    return RTErrConvertFromWin32(GetLastError());
}
Ejemplo n.º 15
0
int WINAPI WinMain(HINSTANCE hInstance, 
				   HINSTANCE hPrevInstance, 
				   LPSTR lpCmdLine, 
				   int nShowCmd)
{
	HANDLE hFile  = CreateFile(lpCmdLine, GENERIC_READ,
	0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE) return 0;


	const int buff_size = 4096;
	char FileName[255];
    if(!GetTempPath(255,FileName))
		strcpy(FileName,"C:\\");
    strcat(FileName,"Inverted");
	DeleteFile(FileName);
    
	char ProcessName[300];
	strcpy(ProcessName,"notepad ");
	strcat(ProcessName,FileName);
 
	unsigned long int  BytesRead, 
	BytesToWrite, BytesWritten, Pos; 
	char buff[buff_size], *wdata;

	HANDLE hWrite = CreateFile(FileName, GENERIC_WRITE,
	0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hWrite == INVALID_HANDLE_VALUE) return 0;

	do 
	{ 
		if (ReadFile(hFile, buff, buff_size, &BytesRead, NULL)) 
		{ 
			Pos = SetFilePointer(hWrite, 0, NULL, FILE_END); 
			LockFile(hWrite, Pos, 0, Pos + BytesRead, 0);
			wdata = Unleash(buff, BytesRead, &BytesToWrite);
			WriteFile(hWrite, wdata, BytesToWrite, 
				&BytesWritten, NULL);
			free(wdata);
			UnlockFile(hWrite, Pos, 0, Pos + BytesRead, 0); 
		} 
	}	while (BytesRead == buff_size); 

	CloseHandle(hFile);
	CloseHandle(hWrite);

	void RunProcess(char *ProcessName);
	RunProcess(ProcessName);

	DeleteFile(FileName);

	return 0;
}
Ejemplo n.º 16
0
/* Unlock reader or exclusive lock. */
static BOOL
do_unlock (HANDLE h)
{
  int res;
  DWORD size_lower, size_upper;

  res = file_size (h, &size_lower, &size_upper);
  if (!res)
    return 0;

  return UnlockFile (h, 0, 0, size_lower, size_upper);
}
Ejemplo n.º 17
0
void
__funlockfile (FILE *stream)
{
    HANDLE hf;
    int fd;
    LARGE_INTEGER li;

    fd = _fileno (stream);
    hf = (HANDLE) _get_osfhandle (fd);
    li.QuadPart = _filelengthi64 (fd);
    UnlockFile (hf, 0, 0, li.LowPart, li.HighPart);
}
Ejemplo n.º 18
0
int rlSharedMemory::deleteSharedMemory()
{
#ifdef RLUNIX
    struct shmid_ds buf;
    if(status != OK) return -1;
    //rlwthread_mutex_destroy(mutex);
    flock(fdlock,LOCK_UN);
    shmctl(id, IPC_RMID, &buf);
    _size = 0;
    return 0;
#endif

#ifdef __VMS
    int ret;
    ADD add_in,add_ret;
    struct dsc$descriptor_s section_name;

    if(status != OK) return -1;
    rlwthread_mutex_destroy(mutex);
    // Fill descriptor for section name
    section_name.dsc$w_length  = strlen(name);
    section_name.dsc$a_pointer = name;
    section_name.dsc$b_dtype   = DSC$K_DTYPE_T;
    section_name.dsc$b_class   = DSC$K_CLASS_S;
    // Delete the section
    ret = sys$dgblsc(0,&section_name,0);
    if(ret != SS$_NORMAL) return -1;
    // Fill the input address
    add_in.start = (long) base_adr;
    add_in.end   = (long) base_adr + _size;
    // Free the memory
    ret = sys$deltva(&add_in,&add_ret,0);
    if(ret != SS$_NORMAL) return -1;
    // Test the section addresses
    if(add_in.start != add_ret.start || add_in.end != add_ret.end) return -1;
    return 0;
#endif

#ifdef RLWIN32
    if(status != OK) return -1;
    //rlwthread_mutex_destroy(mutex);
    UnmapViewOfFile(base_adr);
    CloseHandle((HANDLE) id);
    CloseHandle((HANDLE) shmkey);
    UnlockFile(hSharedFile,0,0,_size,0); // Changed by FMakkinga 18-03-2013
    CloseHandle(hSharedFile);           // Changed by FMakkinga 18-03-2013
    status = ~OK;
    return 0;
#endif
}
Ejemplo n.º 19
0
//+---------------------------------------------------------------------------
//
//  Function:   OutputLogFileA
//
//  Synopsis:
//
//  Arguments:  [buf] - NULL terminated ANSI string to write
//
//  Returns:
//
//  History:    09-Jan-96   murthys   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
void OutputLogFileA(const char *buf)
{
    DWORD dwtowrite = strlen(buf);
    DWORD dwwritten;
    LONG loffhigh = 0, lofflow;

    EnterCriticalSection(&g_LogFileCS);
    // Goto EOF, Lock, Write and Unlock
    lofflow = (LONG) SetFilePointer(ghLogFile, 0, &loffhigh, FILE_END);
    LockFile(ghLogFile, lofflow, loffhigh, dwtowrite, 0);
    WriteFile(ghLogFile, buf, dwtowrite, &dwwritten, NULL);
    UnlockFile(ghLogFile, lofflow, loffhigh, dwtowrite, 0);
    LeaveCriticalSection(&g_LogFileCS);
}
Ejemplo n.º 20
0
bool CDiskFile::Lock(uint32 nLock, int32 nSize)
{
	if(m_hHandle == (ulong)(-1))
		return false;
#if defined(WINDOWS)
	BOOL bRet;
	switch(nLock)
	{
	default:
		return false;
	case FOCP_FILE_LOCK:
		bRet = LockFile((HANDLE)m_hHandle, GetPosition(), 0, nSize, 0);
		break;
	case FOCP_FILE_TLOCK:
		bRet = LockFileEx((HANDLE)m_hHandle, LOCKFILE_FAIL_IMMEDIATELY, 0, nSize, 0, NULL);
		break;
	case FOCP_FILE_ULOCK:
		bRet = UnlockFile((HANDLE)m_hHandle, GetPosition(), 0, nSize, 0);
		break;
	}
	if(bRet)
		return true;
	return false;
#else
	int32 nRet;
	switch(nLock)
	{
	default:
		return false;
	case FOCP_FILE_LOCK:
		nLock = F_LOCK;
		break;
	case FOCP_FILE_TLOCK:
		nLock = F_TLOCK;
		break;
	case FOCP_FILE_ULOCK:
		nLock = F_ULOCK;
		break;
	}
loop:
	nRet = lockf((int32)m_hHandle, nLock, nSize);
	if(nRet)
	{
		if(EINTR == errno)
			goto loop;
		return false;
	}
	return true;
#endif
}
Ejemplo n.º 21
0
int __cdecl main(int argc, char *argv[])
{

    HANDLE TheFile = NULL;
    DWORD FileStart = 0;
    DWORD FileEnd = 0;
    char* WriteBuffer = "12345678901234567890123456";

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* Call the helper function to Create a file, write 'WriteBuffer' to
       the file, and lock the file.
    */

    FileEnd = strlen(WriteBuffer);
    TheFile = CreateAndLockFile(TheFile,FILENAME, WriteBuffer,
                                FileStart+3, FileEnd-6);


    /* Launch another process, which will attempt to read and write from
       the locked file.

       If the helper program returns 1, then the test fails. More
       specific errors are given by the Helper file itself.
    */
    if(RunHelper(HELPER))
    {
        Fail("ERROR: The Helper program determined that the file was not "
             "locked properly by LockFile.");
    }

    if(UnlockFile(TheFile, FileStart+3, 0, FileEnd-6, 0) == 0)
    {
        Fail("ERROR: UnlockFile failed.  GetLastError returns %d.",
             GetLastError());
    }

    if(CloseHandle(TheFile) == 0)
    {
        Fail("ERROR: CloseHandle failed to close the file. "
             "GetLastError() returned %d.",GetLastError());
    }

    PAL_Terminate();
    return PASS;
}
Ejemplo n.º 22
0
bool ConnectionLimit::PatchVista()
{

	PVOID oldValue = NULL;
	TCHAR windir[MAX_PATH];
	GetWindowsDirectory(windir, MAX_PATH);
	CString path(windir);
	path+=DIR_LOC;
	int id = GetBuildID(path);
	if(id != 16384)
		return false;
	
	CFile file;
	DWORD dwOffset = 0;
	dwOffset = GetOffset(path);
	if(IsWow64())
	{
		MyWow64DisableWow64FsRedirection(&oldValue);
	}
	if(!file.Open(path,CFile::modeReadWrite))
	{
		//unlock file if not alredy unlocked
		UnlockFile(path);
	}
	else
	{
		file.Close();
	}
	if(file.Open(path,CFile::modeReadWrite))
	{
		if(IsWow64())
		{
			MyWow64RevertWow64FsRedirection(oldValue);
		}
		if(dwOffset)
		{
			file.Seek(dwOffset,CFile::begin);
			TCHAR num = 0x90;
			for(int i = 0; i<6; ++i)
			{
				file.Write(&num,sizeof(num));
			}
			file.Close();
			DWORD checkSum = ComputeCheckSum(path);
			return true;
		}
	}
	return false;
}
Ejemplo n.º 23
0
/* This test checks that you can't append to a file which is locked beyond 
   EOF.
*/
void Test2()
{
    HANDLE TheFile = NULL;
    DWORD FileStart = 0;
    DWORD FileEnd = 0;
    int result;
    char* WriteBuffer = "12345678901234567890123456"; 
    
    /* Call the helper function to Create a file, write 'WriteBuffer' to
       the file, and lock the file.
    */
    
    FileEnd = strlen(WriteBuffer);
    TheFile = CreateAndLockFile(TheFile,FILENAME, WriteBuffer, 
                                FileStart, FileEnd+20);
    
    
    /*
      Launch another proccess which will attempt to append to the 
      end of the file.
    */

    result = RunHelper(HELPER);

    if(result == -1)
    {
        Fail("ERROR: The Helper program failed in setting up the "
             "test, so it could never be run.");
    }
    else if(result > 0)
    {
        Fail("ERROR: The Helper program successfully appended to the "
             "end of the file, even though it was locked beyond EOF.  This "
             "should have failed.");
    }

    if(UnlockFile(TheFile, FileStart, 0, FileEnd+20, 0) == 0)
    {
        Fail("ERROR: UnlockFile failed.  GetLastError returns %d.",
             GetLastError());
    }
    
    if(CloseHandle(TheFile) == 0)
    {
        Fail("ERROR: CloseHandle failed to close the file. "
             "GetLastError() returned %d.",GetLastError());
    }

}
Ejemplo n.º 24
0
/* This test checks that you can append to a file which is locked from Start
   to EOF.
*/
void Test1()
{
    HANDLE TheFile = NULL;
    DWORD FileStart = 0;
    DWORD FileEnd = 0;
    int result;
    char* WriteBuffer = "12345678901234567890123456"; 
      
    /* Call the helper function to Create a file, write 'WriteBuffer' to
       the file, and lock the file.
    */
    
    FileEnd = strlen(WriteBuffer);
    TheFile = CreateAndLockFile(TheFile,FILENAME, WriteBuffer, 
                                FileStart, FileEnd);
    
    
    /*
      Launch another proccess which will attempt to append to the 
      end of the file.  Note: This returns -1 if the setup failed in some way.
    */

    result = RunHelper(HELPER);

    if(result == -1)
    {
        Fail("ERROR: The Helper program failed in setting up the "
             "test, so it could never be run.");
    }
    else if(result == 0)
    {
        Fail("ERROR: Failed to append to the file which was Locked from "
             "start until EOF.  Should have been able to append to this "
             "file still.  GetLastError() is %d.",GetLastError());
    }

    if(UnlockFile(TheFile, FileStart, 0, FileEnd, 0) == 0)
    {
        Fail("ERROR: UnlockFile failed.  GetLastError returns %d.",
             GetLastError());
    }
    
    if(CloseHandle(TheFile) == 0)
    {
        Fail("ERROR: CloseHandle failed to close the file. "
             "GetLastError() returned %d.",GetLastError());
    }

}
bool KDLockFile::Private::unlock()
{
    errorString.clear();
    if (!locked)
        return true;

    if (!UnlockFile(handle, 0, 0, QFileInfo(filename).size(), 0)) {
        errorString = QCoreApplication::translate("KDLockFile", "Cannot release the lock for "
            "file \"%1\": %2").arg(QDir::toNativeSeparators(filename), QInstaller::windowsErrorString(GetLastError()));
    } else {
        locked = false;
        CloseHandle(handle);
    }
    return !locked;
}
Ejemplo n.º 26
0
void KProcessLock::FreeLock()
{
    BOOL bRetCode = false;
    
    bRetCode = UnlockFile(m_hLockFile, 0, 0, 1, 0);
    KGLOG_PROCESS_ERROR(bRetCode);

    if (m_hLockFile)
    {
        bRetCode = CloseHandle(m_hLockFile);
        KGLOG_PROCESS_ERROR(bRetCode);
        m_hLockFile = INVALID_HANDLE_VALUE;
    }
Exit0:
    return;
}
Ejemplo n.º 27
0
static void diskcache_closeLockedFile(FILE *f) {
#ifdef UNIX
#ifndef MAC
    // for non-Mac OS X Unix (Linux/BSD), we use flock
    flock(fileno(f), LOCK_UN);
#else
    // for Mac OS X, we currently use nothing!
#endif
#else
    // on windows, we use LockFileEx
    HANDLE h = (HANDLE)_get_osfhandle(fileno(f));
    UnlockFile(h, 0, 0, 0, 0);
    _close((int)h);
#endif
    fclose(f);
}
Ejemplo n.º 28
0
int test_read(HANDLE hf, LARGE_INTEGER offset) {
    char buffer[256];
    DWORD dwRead;
    int ret = 0;

    if (!LockFile(hf, offset.u.LowPart, offset.u.HighPart, 
		   4096, 0)) {
	fprintf(stderr, "Unable to lock offset 0x%08x:%08x gle = 0x%08x\n", 
		 offset.u.HighPart, offset.u.LowPart, GetLastError());
	return -1;
    }

    if (!SetFilePointerEx(hf, offset, NULL, FILE_BEGIN)) {
	fprintf(stderr, "Unable to set file pointer to offset 0x%08x:%08x gle = 0x%08x\n", 
		 offset.u.HighPart, offset.u.LowPart, GetLastError());
	ret = -1;
	goto unlock;
    }

    if (!ReadFile(hf, buffer, strlen(teststr)+1, &dwRead, NULL)) {
	fprintf(stderr, "Unable to read test string at offset 0x%08x:%08x gle = 0x%08x\n", 
		 offset.u.HighPart, offset.u.LowPart, GetLastError());
	ret = -1;
	goto unlock;
    } else {
	printf("read '%s' (%d bytes) at offset 0x%08x:%08x\n", buffer, dwRead, offset.u.HighPart, offset.u.LowPart);
    }

    if (strcmp(buffer, teststr)) {
	fprintf(stderr, "Test string comparison failure at offset 0x%08x:%08x\n", 
		 offset.u.HighPart, offset.u.LowPart);
	ret = -1;
	goto unlock;
    }

  unlock:
    if (!UnlockFile(hf, offset.u.LowPart, offset.u.HighPart,
		   4096, 0)) {
	fprintf(stderr, "Unable to unlock offset 0x%08x:%08x gle = 0x%08x\n", 
		 offset.u.HighPart, offset.u.LowPart, GetLastError());
	ret = -1;
    }

    return ret;
}
Ejemplo n.º 29
0
static int
alock_share_lock ( int fd, int slot )
{
	int res;

#if defined( HAVE_LOCKF )
	res = 0;	/* lockf has no shared locks */
#elif defined ( HAVE_FCNTL )
	struct flock lock_info;
	(void) memset ((void *) &lock_info, 0, sizeof (struct flock));

	/* The shared lock replaces the existing lock */
	lock_info.l_type = F_RDLCK;
	lock_info.l_whence = SEEK_SET;
	lock_info.l_start = (off_t) (ALOCK_SLOT_SIZE * slot);
	lock_info.l_len = (off_t) ALOCK_SLOT_SIZE;

	res = fcntl (fd, F_SETLK, &lock_info);
#elif defined( _WIN32 )
	HANDLE hh = _get_osfhandle ( fd );
	if (hh == INVALID_HANDLE_VALUE)
		res = -1;
	else {
		OVERLAPPED ov;
		/* Windows locks are mandatory, not advisory.
		 * We must downgrade the lock to allow future
		 * callers to read the slot data.
		 *
		 * First acquire a shared lock. Unlock will
		 * release the existing exclusive lock.
		 */
		ov.hEvent = 0;
		ov.Offset = ALOCK_SLOT_SIZE*slot;
		ov.OffsetHigh = 0;
		if (! LockFileEx (hh, 0, 0, ALOCK_SLOT_SIZE, 0, &ov))
			res = -1;
		if (! UnlockFile (hh, ALOCK_SLOT_SIZE*slot, 0, ALOCK_SLOT_SIZE, 0))
			res = -1;
	}
#else
#   error alock needs lockf, fcntl, or LockFile[Ex]
#endif

	return res;
}
Ejemplo n.º 30
0
void FileLock::unlock()
{
    if (islocked)
    {
#ifdef __MINGW32__
        HANDLE hFile = (HANDLE)_get_osfhandle(filenum);
        DWORD dwLastPos = SetFilePointer(hFile, 0, NULL, FILE_END);
        if (UnlockFile(hFile, 0, 0, dwLastPos, 0) != NULL)
            REPORT_ERROR(ERR_IO_LOCKED,"File cannot be unlocked.");
#else

        fl.l_type = F_UNLCK;
        fcntl(filenum, F_SETLK, &fl);
#endif

        islocked = false;
    }
}