I have a problem with my code in C that uses CreateProcessA and Wait(...) functions. Everything seems to work fine, except exit code. It's always 0. I know (at least) this part of the code (with exit code) is wrong, but I tried many ways to fix it and none on them actually worked. Also, PIDs, when displaying them in console, sometimes are not where they are supposed to be (for example: There are 3 rows with the same PID, and sometimes there is one extra PID from other group, something like: 6656 6656 1234 6656...). Maybe you guys know the solution. Here is the code:
...//some argument conditions above
STARTUPINFO si;
PROCESS_INFORMATION pi[2];
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
int argument = atoi(argv[1]);
int argument1 = argument - 1;
int argument2 = argument - 2;
char a1[50];
sprintf(a1, "file.exe %d", argument1);
BOOL v1 = CreateProcessA("file.exe", a1, NULL, NULL, FALSE, 0, NULL, NULL, &si, pi+0);
char a2[50];
sprintf(a2, "file.exe %d", argument2);
BOOL v2 = CreateProcessA("file.exe", a2, NULL, NULL, FALSE, 0, NULL, NULL, &si, pi+1);
HANDLE children[2] = { pi[0].hProcess, pi[1].hProcess };
WaitForMultipleObjects(2, children, 1, INFINITE);
for (int i = 1; i >= 0; i--)
{
CloseHandle(pi[i].hProcess);
CloseHandle(pi[i].hThread);
}
unsigned long int exit1 = GetExitCodeProcess(children[0], &exit1);
unsigned long int exit2 = GetExitCodeProcess(children[1], &exit2);
printf("%d \t %d \t %d \t %d \t\n", GetCurrentProcessId(), pi[0].dwProcessId, argument1, exit1);
printf("%d \t %d \t %d \t %d \t\n", GetCurrentProcessId(), pi[1].dwProcessId, argument2, exit2);
printf("%d \t \t \t %d\n\n", GetCurrentProcessId(), exit1 + exit2);
return exit1 + exit2;
}
Thanks for any help.
In this code:
HANDLE children[2] = { pi[0].hProcess, pi[1].hProcess };
WaitForMultipleObjects(2, children, 1, INFINITE);
for (int i = 1; i >= 0; i--)
{
CloseHandle(pi[i].hProcess);
CloseHandle(pi[i].hThread);
}
unsigned long int exit1 = GetExitCodeProcess(children[0], &exit1);
unsigned long int exit2 = GetExitCodeProcess(children[1], &exit2);
One problem is that exit1
and exit2
are being initialized to the return values of GetExitCodeProcess
. That function has a return type of BOOL
and returns 0 (FALSE
) on failure, or a non-zero value (presumably 1 (TRUE
)) on success. Since the process handles have already been closed in the preceding for
loop, GetExitCodeProcess
will return the failure value 0.
Try changing it to to the following:
HANDLE children[2] = { pi[0].hProcess, pi[1].hProcess };
WaitForMultipleObjects(2, children, 1, INFINITE);
DWORD exit1, exit2;
GetExitCodeProcess(children[0], &exit1);
GetExitCodeProcess(children[1], &exit2);
for (int i = 1; i >= 0; i--)
{
CloseHandle(pi[i].hProcess);
CloseHandle(pi[i].hThread);
}