为了尝试如何使用Win32应用程序接口编程,我编写了一个创建进程的程序。然后我想检查我的进程是否在等待新创建的进程,关闭句柄,然后再次检查WaitForSingleObject (第二个进程休眠了700ms)
第一个过程:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
bool ret;
bool retwait;
STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);
PROCESS_INFORMATION pro2info;
wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe";
ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
NULL, &startupinfo, &pro2info);
cout<<"hProcess: "<<pro2info.hProcess<<endl;
cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl;
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true)
cout<<"waitprocess:true"<<endl; //The process is finished
else
cout<<"waitprocess:false"<<endl;
CloseHandle (pro2info.hProcess);//prozesshandle schließen, "verliert connection"
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) //When the process has finished
cout<<"waitprocess:true"<<endl;
else
cout<<"waitprocess:false"<<endl;
//cout<<GetLastError()<<endl; //Output the last error.
ExitProcess(0);
}第二个过程:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
int b;
b = GetCurrentProcessId();
cout << b << endl;
cout << "Druecken Sie Enter zum Beenden" << endl;
cin.get();
//Wait until the user confirms
Sleep (700);
ExitProcess(0);
cout<<"test";
}第一个过程打印false,false;但它应该打印true,false。
我没有使用if-else语句,而是使用了以下语句:
//switch(WaitForSingleObject (pro2info.hProcess, INFINITE)){
// case WAIT_OBJECT_0: cout << "ja";
// break;
// case WAIT_FAILED:cout << "nein";
// break;
// case WAIT_TIMEOUT:
// break;
//}
// cout<<"waitprocess:true"<<endl;//prozess ist fertig
//else
// cout<<"waitprocess:false"<<endl;这似乎是可行的。我的if-else语句做错了什么?
发布于 2010-04-01 00:08:33
您确实需要注意API函数返回值的含义。您不能忽略来自CreateProcess()的FALSE返回。WaitForSingleObject()可以返回多个值,如果等待成功完成,则返回0。这会让你打印出"false“。
发布于 2010-04-01 00:07:28
根据MSDN, WaitForSingleObject的说法,如果等待没有中止,将返回WAIT_OBJECT_0。如果您查看文档,WAIT_OBJECT_0的值恰好是0x00000000L,这恰好是通常转换为false而不是true的值。因此,您的比较失败。
将WaitForSingleObject的返回值提升为bool不是一个好主意,因为您会得到几个可能具有启发性的非零返回代码,它们指示等待过期的原因。
如果您仍然希望将上面的代码保留为使用布尔检查,请将测试改为!WaitForSingleObject(...)。
发布于 2010-04-01 00:07:46
我认为你自己回答了你的问题。关键是WaitForSingleObject并没有返回true或false,而是WAIT_OBJECT_0等人。
因此,不是
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true)你需要
if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==WAIT_OBJECT_0)https://stackoverflow.com/questions/2554447
复制相似问题