I want to port my linux code to windows. I don't want use cygwin or mingw. I would like to do this via WinApi. So who can help me to write waitpid() analog under windows?
Asked
Active
Viewed 6,669 times
2 Answers
5
CreateProcess
the way to create a new process. Its output is PROCESS_INFORMATION structure. WaitForSingleObject
could wait for the end of the process.
Here is the example from MSDN library (GetExitCodeProcess
was added.):
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD exit_code = 0;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // 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;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Get exit code
GetExitCodeProcess( pi.hProcess, &exit_code );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}

Naszta
- 7,560
- 2
- 33
- 49
-
1This is not news for me @Naszta. I'm not asking about creating process. I'm asking about waiting untill process finishes and getting its exit status. The code you post here doesn't give me exit status of spawned process. – Mihran Hovsepyan Mar 30 '11 at 15:29
-
@Mihran Hovsepyan: you should use: `GetExitCodeProcess` function. See: http://msdn.microsoft.com/en-us/library/ms683189%28v=VS.85%29.aspx – Naszta Mar 30 '11 at 18:07
3
You can use WaitForSingleObject if you have a process handle. You should have obtained that when creating the child process.

Dan
- 354
- 1
- 4
-
how get status via WaitForSingleObject? The question not about wait(), its about waitpid(). – Mihran Hovsepyan Mar 30 '11 at 14:15
-
1You use WaitForSingleObject to wait it's termination, you use GetExitCodeProcess to get it's exit code - http://msdn.microsoft.com/en-us/library/ms683189(v=VS.85).aspx – Anya Shenanigans Mar 30 '11 at 14:27
-
Or specify a 0 timeout to get the state. Or use OpenProcess() to get the process handle. – Hans Passant Mar 30 '11 at 15:32