为了尝试使用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);
}
第二道工序:
#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
语句有什么错? 最佳答案
您确实需要注意API函数返回值的含义。您不能忽略CreateProcess()的FALSE返回。 WaitForSingleObject()可以返回多个值,如果等待成功完成,则返回0。这使您打印“false”。
关于c++ - 如何使用WaitForSingleObject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2554447/