I wrote a code in C that takes input argument, creates two child processes by using CreateProcessA(...), but it is not always working as it should. In console it should be displayed like
:
and most of the time it is like that. But sometimes...
this happens (some PIDs are not getting into right "groups"). I tried to fix that in many different ways (my Linux's code using forks(), that does the same, works like a charm by the way), but any change did not fix the problem.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<windows.h>
#include<tchar.h>
#include<process.h>
#include<processthreadsapi.h>
int main(int argc, char* argv[], char** envp)
{
if (argc != 2)
{
fprintf(stderr, "Wrong number of input arguments!\n");
return 1;
}
char* endptr;
int secs = strtol(argv[1], &endptr, 10);
if (secs <= 0 || *endptr != '\0')
{
fprintf(stderr, "Input argument is not a natural number!\n");
return 2;
}
if (atoi(argv[1]) < 1 || atoi(argv[1]) > 13)
{
fprintf(stderr, "Input argument must be between 1 and 13\n");
return 3;
}
if (atoi(argv[1]) == 1 || atoi(argv[1]) == 2)
{
return 1;
}
//CreateProcessA() etc part is here
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, "thisprogram.exe %d", argument1);
BOOL v1 = CreateProcessA("thisprogram.exe", a1, NULL, NULL, 0, 0, NULL, NULL, &si, pi+0);
char a2[50];
sprintf(a2, "thisprogram.exe %d", argument2);
BOOL v2 = CreateProcessA("thisprogram.exe", a2, NULL, NULL, 0, 0, NULL, NULL, &si, pi+1);
WaitForSingleObject(pi[0].hProcess, INFINITE);
WaitForSingleObject(pi[1].hProcess, INFINITE);
DWORD exit1;
GetExitCodeProcess(pi[0].hProcess, &exit1);
DWORD exit2;
GetExitCodeProcess(pi[1].hProcess, &exit2);
DWORD pid = GetCurrentProcessId();
printf("%d \t %d \t %d \t %d \t\n", pid, pi[0].dwProcessId, argument1, exit1);
printf("%d \t %d \t %d \t %d \t\n", pid, pi[1].dwProcessId, argument2, exit2);
printf("%d \t \t \t %d\n\n", GetCurrentProcessId(), exit1 + exit2);
for (int i = 0; i >= 0; i--)
{
CloseHandle(pi[i].hProcess);
CloseHandle(pi[i].hThread);
}
return exit1+exit2;
}
Shown examples' input argument is 5. For 4 it always work fine. For 6 and more - problem is getting bigger and bigger. I don't think it is a "normal" thing. Any ideas to fix the problem?
Thanks for any help.