0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コマンドプロンプトで複数プロセスの同一ファイル出力

Last updated at Posted at 2021-01-14

コマンドプロンプトで複数プロセスから同じログファイルにまとめて出力って意外と大変そう。。。
ちょっと考えたら考慮することが多い。。。

  • 単純にリダイレクトだと長い処理にファイルロックされてミスりそう

  • 処理事にファイル出力してログファイルに結合、結合ミスったらリトライしたい

  • リトライで永久ループではまったときのために pid で kill したい、自身の pid 取得がやっかい


処理の流れとしては以下の感じで対応、たぶん大丈夫そう!

@echo off
set LOGFILE=C:\logs\cmd.log
set LOGSUBFILE=C:\logs\cmd_subxxx.log
set PIDFILE=C:\logs\pid.log

rem pid出力(powershell 実行して親プロセス取得で cmd のpid取得)
rem # taskkill /pid %pid% で強制終了できるように念のため...
powershell "Get-WmiObject win32_process -filter processid=$pid | ForEach-Object{$_.parentprocessid;}" > %PIDFILE%

rem 処理事のログファイル
echo 実際の処理(コマンド読んだり、ps実行したり) > %LOGSUBFILE%

:RETRYCOPY
    rem ログファイルに結合(失敗したらリトライ)
    copy /b %LOGFILE% + %LOGSUBFILE% %LOGFILE%
    if not "%ERRORLEVEL%" == "0" (timeout 1 & goto RETRYCOPY)

rem pid, sub ファイルは削除
del %PIDFILE%
del %LOGSUBFILE%

exit 0

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?