为了试用如何使用Win32 API进行编程,我编写了一个创建进程的程序.然后我想检查我的进程是否等待新创建的进程,关闭句柄然后再次检查WaitForSingleObject(第二个进程正在休眠700毫秒)
第一个过程:
#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);
}
Run Code Online (Sandbox Code Playgroud)
第二个过程:
#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";
}
Run Code Online (Sandbox Code Playgroud)
第一个进程打印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;
Run Code Online (Sandbox Code Playgroud)
这似乎有效.我的if-else陈述怎么办?
Han*_*ant 21
您真的需要注意API函数返回值的含义.您不能忽略CreateProcess()的FALSE返回.WaitForSingleObject()可以返回多个值,如果等待成功完成则返回0.这使你打印"假".
根据MSDN,如果等待没有中止,WaitForSingleObject将返回WAIT_OBJECT_0.如果您查看文档,则WAIT_OBJECT_0的值恰好是0x00000000L,这恰好是通常转换为的值false,而不是true.因此你的比较失败了.
推进的返回值WaitForSingleObject的bool是恕我直言,不是一个好主意,因为你得到指示,为什么等待过期几个潜在照明非零返回代码.
如果您仍希望将上述代码保留为使用布尔检查,请将测试更改为!WaitForSingleObject(...).
| 归档时间: |
|
| 查看次数: |
60565 次 |
| 最近记录: |