Concurrent File write between processes

后端 未结 2 845
遥遥无期
遥遥无期 2021-01-25 22:54

I need to write log data into a single file from different processes.

I am using Windows Mutex which needs Common Language Runtime support for it.

Mute         


        
2条回答
  •  伪装坚强ぢ
    2021-01-25 23:40

    Actually you don't need to use a separate mutex at all, you can just use the file itself. When a file is opened with the CreateFile API call (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396), the call takes a parameter called dwShareMode which specifiew what concurrent access is allowed by other processes. A value of 0 would prevent other processes from opening the file completely.

    Pretty much all APIs to open a file map to CreateFile under the hood, so clr might be doing the right thing for you when you open a file for writing already.

    In the C runtime there is also _fsopen which allows you to open a a file with the sharing flags.

    I'd recommend you to test what the default sharing mode is when you open your file from C#. If it does not prevent simultaneous open for writing by default, use _fsopen from C (or maybe there is an appropriate C# function).

提交回复
热议问题