Es posible que no funcione correctamente cuando se utiliza un programa que no está conectado a la consola, porque esa aplicación aún podría estar ejecutándose mientras crees que tienes el código de salida. Una solución de hacerlo en C++ se parece a continuación:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"
int _tmain(int argc, TCHAR *argv[])
{
CString cmdline(GetCommandLineW());
cmdline.TrimLeft('\"');
CString self(argv[0]);
self.Trim('\"');
CString args = cmdline.Mid(self.GetLength()+1);
args.TrimLeft(_T("\" "));
printf("Arguments passed: '%ws'\n",args);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if(argc < 2)
{
printf("Usage: %s arg1,arg2....\n", argv[0]);
return -1;
}
CString strCmd(args);
// Start the child process.
if(!CreateProcess(NULL, // No module name (use command line)
(LPTSTR)(strCmd.GetString()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d)\n", GetLastError());
return GetLastError();
}
else
printf("Waiting for \"%ws\" to exit.....\n", strCmd);
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
int result = -1;
if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
{
printf("GetExitCodeProcess() failed (%d)\n", GetLastError());
}
else
printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return result;
}
También se preguntó en SuperUser: [¿Cómo comprobar el código de salida del último comando en el archivo por lotes?] (Http://superuser.com/q/194662/126252) – Deanna