进程间读取器写入器锁(或文件句柄和访问被拒绝)

时间:2009-05-08 17:17:50

标签: vb.net file locking file-security

好的,首先是一些背景知识。我们需要一个进程间读取器/写入器锁。我们决定使用一个文件并使用LockEx和UnlockEx锁定第一个字节。该类在创建时在系统临时文件夹中创建一个文件。使用readwrite访问创建文件并共享读写|删除。我们还指定了DeleteOnClose,因此我们不会留下大量的临时文件。显然,AcquireReader和AcquireWriter使用适当的标志调用LockEx,而ReleaseLock调用UnlockEx 我们已经使用一个小型应用程序测试了这个类,您可以运行多个实例并且它可以完美地运行。使用它的应用程序有一个问题,我们已经设法在另一个小测试应用程序中重新生成。在伪代码中它是

Create InterProcessReaderWriter
Dispose InterProcessReaderWriter without acquiring any locks
Launch a child process which takes a reader lock

第一次运行时,它运行正常。如果您再次尝试运行它,当第一次子进程仍然保持锁定时,我们在尝试打开文件时会收到UnauthorisedAccessException。
这似乎是权限问题,而不是共享冲突,但此测试用例中的所有进程都以同一用户身份运行。这里有没有人有任何想法?

我注意到另一个问题,建议使用互斥锁和信号量来实现我们想要的东西。我可能会改变我们的实现,但我仍然想知道造成这个问题的原因。

2 个答案:

答案 0 :(得分:0)

听起来像子进程试图两次访问同一个文件。

临时文件名是唯一的吗?

答案 1 :(得分:0)

为什么不锁定整个文件?而不是第1个字节。下面的示例类具有以下优点:它可以跨不同机器上的进程工作,而不是仅限于一台机器。

这是一个使用下面的lockfilehelper类的简单示例。

Module Module1
    Sub Main()
        Using lockFile As New LockFileHelper("\\sharedfolder\simplefile.lock")
            If lockFile.LockAcquire(1000) Then
                ' Do your work here.
            Else
                ' Manage timeouts here.
            End If
        End Using
    End Sub
End Module

这是Helper类的代码。

Public Class LockFileHelper
    Implements IDisposable
    '-------------------------------------------------------------------------------------------------
    ' We use lock files in various places in the system to provide a simple co-ordination mechanism
    ' between different threads within a process and for sharing access to resources with the same
    ' process running across different machines.
    '-------------------------------------------------------------------------------------------------
    Private _lockFileName As String
    Private _ioStream As IO.FileStream
    Private _acquiredLock As Boolean = False
    Private _wasLocked As Boolean = False
    Public Sub New(ByVal LockFileName As String)
        _lockFileName = LockFileName
    End Sub
    Public ReadOnly Property LockFileName() As String
        Get
            Return _lockFileName
        End Get
    End Property
    Public ReadOnly Property WasLocked() As Boolean
        Get
            Return _wasLocked
        End Get
    End Property
    Public Function Exists() As Boolean
        Return IO.File.Exists(_lockFileName)
    End Function
    Public Function IsLocked() As Boolean
        '-------------------------------------------------------------------------------------------------
        ' If this file already locked?
        '-------------------------------------------------------------------------------------------------
        Dim Result As Boolean = False
        Try
            _ioStream = IO.File.Open(_lockFileName, IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
            _ioStream.Close()
        Catch ex As System.IO.IOException
            ' File is in used by another process.
            Result = True
        Catch ex As Exception
            Throw ex
        End Try

        Return Result
    End Function
    Public Sub LockAcquireWithException(ByVal TimeOutMilliseconds As Int32)
        If Not LockAcquire(TimeOutMilliseconds) Then
            Throw New Exception("Timed out trying to acquire a lock on the file " & _lockFileName)
        End If
    End Sub
    Public Function LockAcquire(ByVal TimeOutMilliseconds As Int32) As Boolean
        '-------------------------------------------------------------------------------------------------
        ' See have we already acquired the lock. THis can be useful in situations where we are passing
        ' locks around to various processes and each process may want to be sure it has acquired the lock.
        '-------------------------------------------------------------------------------------------------
        If _acquiredLock Then
            Return _acquiredLock
        End If

        _wasLocked = False
        Dim StartTicks As Int32 = System.Environment.TickCount
        Dim TimedOut As Boolean = False
        If Not IO.Directory.Exists(IO.Path.GetDirectoryName(_lockFileName)) Then
            IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(_lockFileName))
        End If
        Do
            Try
                _ioStream = IO.File.Open(_lockFileName, IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
                _acquiredLock = True
            Catch ex As System.IO.IOException
                ' File is in used by another process.
                _wasLocked = True
                Threading.Thread.Sleep(100)
            Catch ex As Exception
                Throw ex
            End Try
            TimedOut = ((System.Environment.TickCount - StartTicks) >= TimeOutMilliseconds)
        Loop Until _acquiredLock OrElse TimedOut
        '-------------------------------------------------------------------------------------------------
        ' Return back the status of the lock acquisition.
        '-------------------------------------------------------------------------------------------------
        Return _acquiredLock
    End Function
    Public Sub LockRelease()
        '-------------------------------------------------------------------------------------------------
        ' Release the lock (if we got it in the first place)
        '-------------------------------------------------------------------------------------------------
        If _acquiredLock Then
            _acquiredLock = False
            If Not IsNothing(_ioStream) Then
                _ioStream.Close()
                _ioStream = Nothing
            End If
        End If
    End Sub
    Private disposedValue As Boolean = False        ' To detect redundant calls
    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                Call LockRelease()
            End If

            ' TODO: free shared unmanaged resources
        End If
        Me.disposedValue = True
    End Sub
#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region
End Class