Page 1 of 1

File Locking

Posted: Tue Nov 26, 2019 8:54 am
by wayne-c
The following code unfortunately runs only on Windows with the desired file locking :-(
Any ideas how to get this working on MacOS too?

Code: Select all

; --> compile as exe/app and rund multiple times!

If OpenConsole()
  PrintN("Try to open file")
  FileProcessed = #False
  Repeat
    ; open the file WITHOUT #PB_File_SharedRead Or #PB_File_SharedWrite
    ; for exclusive access
    ; --> this runs ONLY on windows!
    hFile = OpenFile(#PB_Any, GetPathPart(ProgramFilename()) + "lockfiletest.dat", #PB_UTF8)
  	If hFile
  		PrintN("File is open")
  		Delay(1000)
  		Text$ = ReadString(hFile, #PB_File_IgnoreEOL, Lof(hFile))
  		Text$ + FormatDate("%dd.%mm.%yyyy %hh:%ii:%ss", Date()) + #CRLF$
  		PrintN("Content read")
  		Delay(1000)
  		FileSeek(hFile, 0, #PB_Absolute)
  		TruncateFile(hFile)
  		PrintN("File truncated")
  		Delay(1000)
  		WriteString(hFile, Text$)
  		PrintN("Content written")
  		Delay(1000)
  		PrintN("Closing file")
  		CloseFile(hFile)
  		PrintN("File closed")
  		FileProcessed = #True
  	Else
  	  PrintN("Waiting for file")
  	  Delay(500)
  	EndIf
  Until FileProcessed
	CloseConsole()
EndIf

Re: File Locking

Posted: Sun Jan 05, 2020 1:21 pm
by wayne-c
Time to ask again ;-)

Re: File Locking

Posted: Sun Jan 05, 2020 2:29 pm
by deseven
It looks like macOS doesn't support file locking per process. There is a way to make file immutable (i.e. read only), but that's it.

If your app is the only one that will write this file, you can create your own lock system based on process pid and lock files.