Page 1 of 1

Replacing a locked file

Posted: 17 Oct 2023 12:48
by Raptor4248
Hello,

I've got a problem of my own making. A while back I created a bit of a monstrosity of a batch file to automate some tasks and I added this to stop multiple instances.

Code: Select all

@echo off
9>&2 2>nul (call :lockAndRestoreStdErr %* 8>>"%~f0") || (
  echo Only one instance allowed - "%~f0" is already running >&2
  pause
)
exit /b

:lockAndRestoreStdErr
call :main %* 2>&9
exit /b 0

:main
echo Do Stuff....
Credit: https://stackoverflow.com/questions/529 ... t-up-again

Part of my batch file allowed for a future update to it and files it comes with by downloading an update pack and replacing files included as needed. The monstrosity will download a zip file and another batch file to do the update to a temporary location and then the monstrosity launches the downloaded update script using "start" without "/wait" in a new window and exits.

The update script works fine right up until it comes to replacing the file containing the code above, despite the launching batch file having exited the file is still locked somehow and I can't replace it. Once I close the newly launched window that is running the update batch I can edit the monstrosity again, I can't find an alternative way of launching the update script that doesn't seem to inherit the lock I placed on the monstrosity though.

Any ideas?
Thanks!

Re: Replacing a locked file

Posted: 18 Oct 2023 03:35
by Raptor4248
I've put together a simple version of the problem I'm stuck on which hopefully makes more sense than my original explanation. In this example file.cmd cannot be renamed by file_rename.cmd even after file.cmd has exited.

Code: Select all

@echo off
@cd /d "%~dp0"
@title %~f0

Set countdown=5

9>&2 2>nul (call :lockAndRestoreStdErr %* 8>>"%~f0") || (
  echo Only one instance allowed - "%~f0" is already running >&2
  pause
)
exit /b

:lockAndRestoreStdErr
call :main %* 2>&9
exit /b 0

:main

(
	echo @echo off
	echo @title %%~f0
	echo echo Renaming %cd%\%~nx0 to %cd%\renamed_%~n0.cmd in %countdown% seconds.
	echo timeout /t %countdown% /nobreak
	echo rename "%cd%\%~nx0" renamed_%~n0.cmd
	echo echo.
	echo pause
	echo exit
) > "%cd%\%~n0_rename.cmd"

echo Launching %cd%\%~n0_rename.cmd in %countdown% seconds.
timeout /t %countdown% /nobreak
start "" "%cd%\%~n0_rename.cmd"
exit

Re: Replacing a locked file

Posted: 18 Oct 2023 10:54
by miskox
Maybe you could add a

Code: Select all

timeout /T 10
before replacing the file so you have some time for the parent process to exit.

Saso

Re: Replacing a locked file

Posted: 18 Oct 2023 11:18
by Raptor4248
I thought that too but it fails even after giving it 60 seconds. I forgot to mention it but this happens even when run as administrator.