From: Lars Christensen Date: 2009-12-17T19:41:03+09:00 Subject: Re: Cannot obtain child process exit code on Windows On Wed, Dec 16, 2009 at 8:18 AM, Wi siong Ko wrote: > Hi, > > I would like to obtain the exit code from a child program. But all the > methods I tried were in vain. Here are two files that i used to test. > > C:\> type a.bat > @echo off > exit /b 29 > > C:\> type test.rb > system('a.bat') > puts $? > puts $? >> 8 > exit > > C:\>ruby test.rb > pid 5952 exit 0 > 0 > > Seems like in Windows, Ruby can never see the number 29 anyway. > > Can anyone help me? This is normal, and doesn't have much to do with Ruby. You get the same result in a plain command prompt. When running a batch script from Ruby (or any other program), a new cmd.exe instance must be spawned to launch the batch file: C:\>type a.bat @echo off exit /B 29 C:\>cmd /c a.bat C:\>echo %errorlevel% 0 When you run the batch file directly, you are not setting the exit code, but simply the "errorlevel" of the current cmd instance. There is no process exiting when running a.bat from the command line, so there is no exit code to set by doing "exit /B 29". Ruby gives you the exit code of the "process" - which is "cmd.exe", and you are not asking "cmd.exe" to exit with any code other than 0. You can change your .bat: C:\>type b.bat @echo off exit 29 C:\>cmd /c b.bat C:\>echo %errorlevel% 29 But this .bat will exit your console window if run from the command line. This may help though: http://stackoverflow.com/questions/377407/detecting-how-a-batch-file-was-executed