JFLarvoire / SysToolsLib

A library of Windows and Linux system management tools
Apache License 2.0
329 stars 97 forks source link

[PSService] Error writing in Log from a PSThread and main thread #18

Open Aorimn opened 6 years ago

Aorimn commented 6 years ago

Using Start-PSThread in the timer ticked part of the PSService.ps1 script, I encountered this error:

2018-04-01 13:43:37 20268 NT AUTHORITY\SYSTEM PSService.ps1 -Service # Error at line 368: The process cannot access the file 'C:\WINDOWS\Logs\PSService.log' because it is being used by another process.

I understood this error in the following way: sometimes, the Log function is being called at about the same time within the PSThread and in the main thread, resulting in file locks being put in place by one thread and the other trying to lock it for itself.

I have a patch using the Information stream of the PSThread, instead of the Log function directly, but the drawback is that all logs are retrieved once the PSThread is terminated, not in live. The drawback makes it not really satisfying, from my point of view, so if you have any thought or idea to solve this, I'm all ears. If not, I'll submit the patch in a PR, just tell me.

Note that this error makes the PS script terminating, but not the service exe stub - which doesn't see a thing and live happily ever after, but that's another subject.

JFLarvoire commented 6 years ago

I read this message after that in issue #19, and I now understand why you wanted to turn the exe stub into a monitoring service.

Idea: What about using the event loop in the main thread, and define a new even "LogString", so that only the main thread writes to the log?
The even queuing would naturally ensure that the messages are written in chronological order, without any risk of conflict.