Skip to content

Commit

Permalink
Add pid to batch's random filename
Browse files Browse the repository at this point in the history
Batch's `%RANDOM%` resolution is limited to about a second, so if you are
calling hab multiple times at once you will end up with more than one hab
process using the same temp files and causing errors when the first one
to finish cleans up after itself.

Add the pid to the dirname to address this.
  • Loading branch information
MHendricks committed Feb 26, 2024
1 parent acb456b commit 1a555d8
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions bin/hab.bat
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,22 @@

@ECHO OFF

:: Generate a unique temp file name
:: Generate a unique temp folder to store hab's short term temp .bat files.
:: Batch's %RANDOM% isn't so random, https://devblogs.microsoft.com/oldnewthing/20100617-00/?p=13673
:: So if you are calling hab as a batch of subprocesses, you may run into issues
:: where multiple processes use the same random folder causing the dir to get
:: removed while the later processes finish.

:: 1. To work around this issue we add the current process's PID to the filename.
:: https://superuser.com/a/1746190
for /f "USEBACKQ TOKENS=2 DELIMS==" %%A in (`wmic process where ^(Name^="WMIC.exe" AND CommandLine LIKE "%%%%TIME%%%%"^) get ParentProcessId /value`) do set "PID=%%A"
rem echo PID: %PID%
rem timeout 10

:: 2. We also add a random number to hopefully reduce the chance of name conflicts
:uniqLoop
set "temp_directory=%tmp%\hab~%RANDOM%"
set "temp_directory=%tmp%\hab~%RANDOM%-%PID%"
:: If the folder already exists, re-generate a new folder name
if exist "%temp_directory%" goto :uniqLoop

:: Create the launch and config filenames we will end up using
Expand Down

0 comments on commit 1a555d8

Please sign in to comment.