C++标准库没有这样的支持.您需要操作系统API才能执行此操作.如果这是Windows,那么您将使用CreateToolhelp32Snapshot(),然后使用Process32First和Process32Next来迭代正在运行的进程.要注意不可避免的竞争条件,这个过程可能会在你找到它的时候退出.
我刚刚根据汉斯的建议创建了一个。像冠军一样工作!
哦,这是基本代码。
请您必须添加 CStrings sAppPath 和 sAppName。
StartProcess 是一个小函数,它使用 CreateProcess 并返回 PID(此处未使用)。您需要更换它。
这不是一个完整的程序,只是使用 Hans 建议查找程序是否正在运行的代码。一个有趣的测试是将路径设置为 c:\windows\,将应用程序设置为 notepad.exe,并将其设置为 10 秒。
#include <tlhelp32.h>
PROCESSENTRY32 pe32 = {0};
HANDLE hSnap;
int iDone;
int iTime = 60;
bool bProcessFound;
while(true) // go forever
{
hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
pe32.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnap,&pe32); // Can throw away, never an actual app
bProcessFound = false; //init values
iDone = 1;
while(iDone) // go until out of Processes
{
iDone = Process32Next(hSnap,&pe32);
if (strcmp(pe32.szExeFile,sAppName) == 0) // Did we find our process?
{
bProcessFound = true;
iDone = 0;
}
}
if(!bProcessFound) // if we didn't find it running...
{
startProcess(sAppPath+sAppName,""); // start it
}
Sleep(iTime*1000); // delay x amount of seconds.
}
Run Code Online (Sandbox Code Playgroud)