我想将我的linux代码移植到Windows。我不想使用cygwin或mingw。我想通过WinApi这样做。那么谁能帮我在windows下编写waitpid()模拟?
答案 0 :(得分:5)
CreateProcess
创建新流程的方式。它的输出是PROCESS_INFORMATION结构。 WaitForSingleObject
可以等待流程结束。
以下是MSDN library的示例(GetExitCodeProcess
已添加。):
#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 );
}
答案 1 :(得分:3)
如果您有进程句柄,则可以使用WaitForSingleObject。你应该在创建子进程时获得它。