Exclusive file locking - SOLVED

4 posts in this topic

#1 ·  Posted (edited)

I've run into the problem where multiple script processes writing to a log file at the same time can interfere with one another. That is, file writes using FileWriteLine are not atomic, so a line of text from one process can have fragments of text from other processes mixed in with it. Exclusive file-locking should take care of the problem.

Looking through the standard UDFs, I see that _WinAPI_LockFile is available, but according to the MSDN documentation it doesn't block - it returns immediately if the lock can't be obtained - and there doesn't seem to be a UDF for the LockFileEx function. I considered writing my own UDF for LockFileEx, but some aspects (e.g., creating the OVERLAPPED structure and its members) look too complex for the amount of time I have available. I think approximating LockFileEx using LockFile could solve my problem, but I'd like to keep it simple while still working reliably. I'm not confident that (e.g.) a simple retry loop to simulate blocking will be adequate.

Any suggestions for a simple way to achieve exclusive file-locking with blocking?

Edited by tremolux66
Mark problem as solved

Share this post

Link to post
Share on other sites

this is what you're looking for:

i have used it successfully in a very much similar scenario to yours.

Share this post

Link to post
Share on other sites

#3 ·  Posted (edited)

Thanks, I'll  give that a try!

Edited by tremolux66

Share this post

Link to post
Share on other sites

Works great - problem solved! All the log messages are stored perfectly. :)

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • mLipok
      By mLipok
      Recently I was working on TeamVierwer API .
      I had a little break, and wanted to check out another platform.
      Here is the result of my attempt:
      #include "GitHubAPI.au3" _GHAPI_AccessToken('') _GHAPI_GetUser("users/mLipok") _GHAPI_GetUserOrganizations("users/mLipok") _GHAPI_RootEndpoints() and GitHubAPI.au3
      #include-once #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 #Tidy_Parameters=/sort_funcs /reel #Region GHAPI.au3 - Header ; #INDEX# ======================================================================================================================= ; Title .........: GitHubAPI UDF ; AutoIt Version : ; Language ......: English ; Description ...: This is an UDF for for communicate with via GitHub RESTful API ; Author(s) .....: mLipok ; Modified ......: ; =============================================================================================================================== #cs Title: GHAPI UDF Filename: GHAPI.au3 Description: This is an UDF for for communicate with via GitHub RESTful API Author: mLipok Modified: Last Update: 2017/05/23 Requirements: AutoIt or higher This is a collection of functions for GitHub API #ce #EndRegion GHAPI.au3 - Header #Region GHAPI.au3 - Include #include <array.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #EndRegion GHAPI.au3 - Include #Region GHAPI.au3 - Declarations Global $oErrorHandler = ObjEvent("AutoIt.Error", "_GHAPI_ErrFunc") Global $__g_sGitHubAPI_BaseUrl = "" ; URL of the GitHub API Global $__g_sGitHubAPI_Version = "v3" ; Put the current API version in here Global Enum _ $GHAPI_ERR_SUCCESS, _ $GHAPI_ERR_GENERAL, _ $GHAPI_ERR_COMERROR, _ $GHAPI_ERR_STATUS, _ $GHAPI_ERR_COUNTER Global Enum _ $GHAPI_EXT_DEFAULT, _ $GHAPI_EXT_PARAM1, _ $GHAPI_EXT_PARAM2, _ $GHAPI_EXT_PARAM3, _ $GHAPI_EXT_COUNTER Global Enum _ $GHAPI_RET_SUCCESS, _ $GHAPI_RET_FAILURE, _ $GHAPI_RET_COUNTER #EndRegion GHAPI.au3 - Declarations #Region GHAPI.au3 - API Functions Func _GHAPI_ErrFunc($oError) ; Do anything here. ConsoleWrite(@ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _ @TAB & "err.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _ @TAB & "err.windescription:" & @TAB & $oError.windescription & @CRLF & _ @TAB & "err.description is: " & @TAB & $oError.description & @CRLF & _ @TAB & "err.source is: " & @TAB & @TAB & $oError.source & @CRLF & _ @TAB & "err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _ @TAB & "err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _ @TAB & "err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _ @TAB & "err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _ @TAB & "err.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF) EndFunc ;==>_GHAPI_ErrFunc Func _GHAPI_AccessToken($sParam = Default) ; ; Local Static $sAccessToken = '' If $sParam <> Default Then $sAccessToken = $sParam Return $sAccessToken EndFunc ;==>_GHAPI_AccessToken Func _GHAPI_GetUser($sUser) Local $oHTTP = __GHAPI_HTTP_Open("GET", $sUser) Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_GetUser Func _GHAPI_GetUserOrganizations($sUser) Local $oHTTP = __GHAPI_HTTP_Open("GET", $sUser & '/orgs') Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_GetUserOrganizations Func _GHAPI_RootEndpoints() Local $oHTTP = __GHAPI_HTTP_Open("GET", '') Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_RootEndpoints #EndRegion GHAPI.au3 - API Functions #Region GHAPI.au3 - INTERNAL Functions Func __GHAPI_HTTP_Open($sMethod, $sCommand, $sURLParameters = '') Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1") Local $sURL = $__g_sGitHubAPI_BaseUrl & "/" & $sCommand & $sURLParameters ;~ __GHAPI_DebugOut("> $sURL=" & $sURL & @CRLF) $oHTTP.Open($sMethod, $sURL, False) If @error Then Return SetError(@error, @extended, Null) $oHTTP.setRequestHeader("Authorization", "Bearer " & _GHAPI_AccessToken()) ; Accept: application/vnd.github.v3+json $oHTTP.setRequestHeader("Accept", "application/vnd.github." & $__g_sGitHubAPI_Version & "+json") ; User-Agent: Awesome-Octocat-App $oHTTP.setRequestHeader("User-Agent", "AutoIt UDF") Return $oHTTP EndFunc ;==>__GHAPI_HTTP_Open Func __GHAPI_HTTP_Send(ByRef $oHTTP, $sSendParameter = Default) If $sSendParameter = Default Then $oHTTP.Send() Else $oHTTP.Send($sSendParameter) EndIf ConsoleWrite('+' & $oHTTP.Status & @CRLF) ConsoleWrite('>' & $oHTTP.StatusText & @CRLF) ConsoleWrite($oHTTP.ResponseText & @CRLF) ConsoleWrite(@CRLF) If @error Then Return SetError(@error, @extended, $GHAPI_RET_FAILURE) ;~ Return SetError($GHAPI_ERR_SUCCESS, $oJSON.Size, $oJSON) EndFunc ;==>__GHAPI_HTTP_Send #EndRegion GHAPI.au3 - INTERNAL Functions #Region GHAPI.au3 - HOWTO / DOCS / HELP #CS #CE #EndRegion GHAPI.au3 - HOWTO / DOCS / HELP  
      This is just a modest start up and not a whole fully workable UDF, just so for a try, but maybe someone will be useful
      If you need to make it workable just ask about specyfic feature.
    • 5ervant
      By 5ervant
      What's the best way to receive file from a desktop app?
      app.exe will execute a cmd with "au3file.exe /path/of/the/file.xml" and the au3file.exe will get and delete that. Or else? THE MOST IMPORTANT PART OF THE QUESTION
      And best way to transfer file to a desktop app?
      au3file.exe do a $_POST request and the app.exe MUST HAVE a local HTTP server that can receive $_POST, but it looks heavy 'cause the app must have a server such XAMPP. au3file.exe execute a cmd with "app.exe /path/of/the/file.xml" and the app.exe will now get that file and delete. Or else?  
    • LeloDragneel
      By LeloDragneel
      Hey guys,
      I'm looking to implement an accurate voice recognition method in my program. I tried to understand the Microsoft SAPI API, read their online documentation and found it very confusing and unclear. (Like seriously, it's so bad and vague, but that's just my opinion). I have also tried using UTTER UDF, but could not get a grasp either, because you know, that's an extension UDF to Microsoft SAPI.
      Let's face it, the Google Speech Recognition is much more accurate than Microsoft SAPI (by far). Right now, I am determined to just use the Google Speech API. I have dug deep in regards to implementing the Google Speech API in AutoIT and I haven't found even one post about it. I suppose it's because the Google Speech API was only recently made available to the public. In case you don't know what I'm talking about, here's the link to google api. On that page, notice that there is language support for various languages such as Java, C#, and PHP. However, there's no support for AutoIT. So my question is; how can I go about implementing the Google Speech API into my AutoIT program? Is it even possible?
      Cheers guys!
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening everyone
      I'm working on this little project for a week, and, what I'm trying to do could be useful for many users as well...
      I'm trying to do a "Report Generator", which reads the data that have to report from a text file (.txt) formatted with this pattern;

      YES, there are 2 semi-colon at the end of the line.

      In detail, Data1 is a date/time stamp with this format: YYYY/MM/DD HH:MM:SS ;

      When the script starts, the user is prompted to choose 2 dates which I'll call as:
      Report_Date_Start; Report_Date_Start. So, the report, should cover all dates between Report_Date_Start AND Report_Date_End.

      And, already at this point, I don't know how to do the query... How can I say to the script:
      SELECT * FROM (.txt) WHERE Data1 BETWEEN Report_Date_Start AND Report_Date_End; ?

      I thought that I could do a _DateDiff, but if the difference between the two dates is months and not days, how can I do the trick?
      Should I make a Switch...Case with the _DateDiff() and see then calculate all the dates between Report_Date_Start AND Report_Date_End... But then, how can I compare the dates in the file with all the dates between Report_Date_Start AND Report_Date_End? I'm going crazy, I know...

      I've already made a "Export Tool", which exports the content of the .txt file in a .db, managed with SQLite... I mean, there I could easily do a query like I did above the thread, but, this "export", for 1080 rows, takes 28 seconds to be done. And, 1080 rows are daily rows that are added every day in the .txt file, so, in a week, the file could be easily 7000+ rows, which means that the "export" would take 3 minutes to be done... And we can go over and over...
      I'll post just for be "complete" what I've done about the export, so, maybe, someone could say how to improve it in terms of efficency...
      Local $aContenutoFileAuditReport = "" _FileReadToArray($sFileAudit_Report, $aContenutoFileAuditReport) If(IsArray($aContenutoFileAuditReport) And Not @error) Then Local $aContenutoFileAuditReport_Splitted = "" Local $sQuery = "" Local $hInizioConteggio = TimerInit() For $i = 1 To UBound($aContenutoFileAuditReport) - 1 $aContenutoFileAuditReport_Splitted = StringSplit($aContenutoFileAuditReport[$i], ";") $sQuery = "INSERT INTO FileDB_Report(DATESTAMP, TIMESTAMP, USER_ID, OBJECT_ID, DESCRIPTION, COMMENT) " & _ "VALUES(" & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[0]) & "," & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[1]) & "," & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[3]) & "," & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[4]) & "," & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[5]) & "," & _ _SQLite_FastEscape($aContenutoFileAuditReport_Splitted[6]) & ");" If(_SQLite_Exec($hFileDB_Report, $sQuery) <> $SQLITE_OK) Then ConsoleWrite("Errore durante l'esecuzione della query #" & $i & @CRLF) Else ConsoleWrite("Query eseguita correttamente #" & $i & @CRLF) EndIf Next ConsoleWrite("Esportazione completata in: " & Round(TimerDiff($hInizioConteggio)/1000, 0) & " secondi") Else MsgBox($MB_ICONERROR, "Errore!", "Errore durante la lettura del file nell'array." & @CRLF & "Errore: " & @error) EndIf I know that I can't do queries from a .txt file...
      I've been writing this post from 18:40 maybe...
      By the way, if @jchd or someone else could tell me if I can import a formatted .txt file in SQLite and then, do queries on the DB, I'd be very happy for that...
      About the report in PDF, I'm talking with @taietel in order to know how to create a PDF.
      I hope someone will help me
      Sorry for the "long" list of questions...
      Thank you for everything you've done for me
      I have to say that this is the community of programming language that I've loved most!
      By the way, I'll be back tomorrow in the morning ( ~ 9:15 a.m. Italian time ), so, excuse me if I can't answer before that time.
      Hope you guys have a wonderful day/night.

      Thanks again

    • ur
      By ur
      We can get a list of file using the below code.
      Local $aFileList = _FileListToArray(@DesktopDir, "*") Is there any option to use the above one recursively to get sub folders and their contents also.??
      And also, is there any way to serialize the above array locally to some file and load it later when we want in another program on another machine so that we can compare its contents with a folder in different machine, which is not network connected also.?