2017-02-27 38 views
0

我有一個批處理腳本start.bat創建鎖定.lock文件(基本上,以驗證腳本運行,通過試圖將其刪除),並開始一堆二級循環批處理腳本(它們在start.bat關閉後繼續運行)。問題是當start.bat關閉時,鎖定的文件保持鎖定狀態,直到所有的輔助腳本都關閉。啓動命令不允許腳本完全關閉,直到二次腳本關閉

問題:是否有任何替代方法沒有,直到二次那些完成鎖定了主要的腳本運行二次批處理腳本?

我覺得這個代碼大部分都是不相關的,但包括它以防有人想測試它。

@echo off 
set "started=" 
<nul >"%~nx0.lock" set /p ".=." ::Rewrite lock file with a single dot 
2>nul (
    9>>"%~f0.lock" (
    set "started=1" 
    call :start 
) 
) 
@if defined started (
    del "%~f0.lock">nul 2>nul 
) else (
    exit //script closes 
) 
exit /b 

:start 
//irrelevant loop logic 
Start pause.bat //Pause command to keep pause.bat open 
//starts other batch files too 

回答

0

好像文件可能仍在使用中?

嘗試:

del /F "%~f0.lock">nul 2>nul 
0

你的問題是繼承句柄。當您啓動重定向激活的進程時,進程將繼承重定向。所以,你需要保持鎖定狀態,但不啓動進程。

你可以試試這個

@echo off 
    setlocal enableextensions disabledelayedexpansion 

    rem Check if this is a lock instance 
    if "%~1"==".LOCK." goto :eof 

    rem Retrieve all the needed data to handle locking 
    call :getCurrentFile f0 
    for %%a in ("%f0%") do set "lockFile=%%~nxa.lock" 
    set "lockID=%random%%random%%random%%random%%random%%random%%random%" 

    rem Try to adquire lock 
    set "started=" 
    2>nul (
     >"%lockFile%" (
      rem We get the lock - start a hidden instance to maintain the lock 
      set "started=1" 
      start "" /b cmd /k""%f0%" .LOCK. %lockID%" 
     ) 
    ) 

    rem Check if the lock was sucessful 
    if not defined started (
     echo lock failed 
     pause 
     goto :eof 
    ) 

    rem Launch the child processes, now detached from lock, as this cmd instance 
    rem is not holding it. The hidden cmd /k instance holds the lock 
    start "" write.exe 
    start "" notepad.exe 
    start "" /wait winver.exe 

    rem Once done, release the locked instance 
    >nul 2>nul (
     wmic process where "name='cmd.exe' and commandline like '%%.LOCK. %lockid%%%'" call terminate 
    ) 

    rem And remove the lock file 
    del "%lockFile%" 

    rem Done 
    goto :eof 

rem To prevent problems: http://stackoverflow.com/q/12141482/2861476   
:getCurrentFile returnVar 
    set "%~1=%~f0" 
    goto :eof 

由於隱藏cmd例如一些變化託管比目前的批處理文件相同的控制檯內,如果您關閉控制檯,鎖被釋放(但鎖定文件不被刪除)