I'm a Winapi/C++ beginner, and I've been stuck for a while on a simple college task.
I have already written a similar program using fork()
from POSIX. My question is, how can Windows separate/identify which process is considered a parent/child using a single .exe
file?
To simplify the problem, I decided to make sure the parent always launches first, waits for all children to finish, and then closes.
Print command line arguments in child processes in a way that each process prints only one arguments and parent waits for them to finish and closes. In short parent only spawns processes, children do the task.
For example, the command-line call would look like this:
untitled.exe a b c
Expected output would be in random order:
Child process #1: a
Child process #2: b
Child process #3: c
Parent finishes...
I've tried passing a single argument to each child process by command-line arguments, so each gets: untitled.exe argv[index]
, where index
stands for argument range [a, b, c]
. This solution is faulty because the parent might get one argument and the child wouldn't spawn.
if (argc <= 2){...}
I though about using a separate .exe
file, but I would like to avoid this solution.
I though about using shared memory, but how do I differentiate the parent from each child in that case?
EDIT:
Minimal referral example:
int _tmain(int argc, TCHAR *argv[]) {
for (int i = 1; i < argc; ++i) {
if (argc <= 2){
//print if only has two arguments and finish
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
CHAR *temp;
sprintf(temp,"%s%s%s",argv[0]," ",argv[i]);//create new command line call to pass to createProcess
if (!CreateProcess(nullptr, // No module name (use command line)
temp, // exe with one argument
nullptr, // Process handle not inheritable
nullptr, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
nullptr, // Use parent's environment block
nullptr, // Use parent's starting directory
&si, // Pointer toa STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
) {
printf("CreateProcess failed (%d).\n", GetLastError());
return 0;
}
else {
std::cout << "Child created" << std::endl;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}