我有一个父进程,我想在一定时间内(比如 N 毫秒)生成子进程。我在 C++(和 Windows)中这样做。
我可以为 CreateProcess 提供一些参数吗?那会在一段时间后杀死它并将控制权返回给父应用程序吗?如果没有,还有其他方法吗?
最佳答案
我可以为 CreateProcess...提供一些参数吗?
是的,您可以将所需的 duration
(N) 与参数 lpCommandLine 传递给要启动的进程。
子进程可以解析lpCommandLine并设置一个定时器
持续时间
。例如,这个计时器可以是 Waitable Timer。或者只是一个带有
Sleep(duration); // waits the duration
ExitProcess(GetLastError()); // exits the "remote" process
线程(子进程内的线程)在 duration
后终止整个子进程。 WaitableTimer 的想法需要频繁调用等待函数。参见 Using Waitable Timer Objects了解详情。
但是:父进程将始终保持“控制”状态。 但是:您还可以 在父进程中进入等待状态,使用等待函数(例如 WaitForSingleObject ,等待子进程句柄实际休眠父进程,直到子进程终止。最重要的是,您可以通过以下方式评估子进程的返回值调用 GetExitCodeProcess function。
所描述的方案可确保最佳执行所需的duration
,但是,您也可以通过命名事件从父进程控制duration
。参见 Using Event Objects了解详情。在这种方法中,父进程可以在 duration
“消耗”时设置一个事件。子进程等待该事件并在事件设置时终止。这种方法可能不太准确,因为 parent 不太清楚 child 的 duration
何时开始。
带有可等待计时器的示例:
父进程:
...
#define CHILD_DURATION 2000 // 2000 ms
HANDLE hProcess;
char ChildName[MAX_PATH];
char CommandLine[MAX_PATH];
sprintf_s(ChildName,MAX_PATH,"MyChild.exe");
sprintf_s(CommandLine,MAX_PATH,"%d",CHILD_DURATION);
// start the child
hProcess = CreateProcess(ChildProcessName,CommandLine,....
if (0 == hProcess)
{
// error with process creation
printf("CreateProcessfailed (%d)\n", GetLastError());
return GetLastError();
}
// and wait for it to finish
if (WAIT_OBJECT_0 == WaitForSingleObject(hProcess,INFINITE)
{
// child finished
} else
{
// error with wait
printf("WaitForSingleObject failed (%d)\n", GetLastError());
return GetLastError();
}
...
子进程:
int main(int argc, char * argv[])
{
HANDLE hWaitableTimer CreateWaitableTimer(NULL,TRUE,NULL);
if (NULL == hWaitableTimer)
{
printf("CreateWaitableTimer failed (%d)\n", GetLastError());
return GetLastError();
}
DWORD dwDuration = atoi(argv[1]);
LARGE_INTEGER liDueTime = -10000 * dwDuration;
// waitable timer due time is in 100 nano second units
// negative values indicate relative time
if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0))
{
printf("SetWaitableTimer failed (%d)\n", GetLastError());
return GetLastError();
}
DWORD dwKeepGoing = TRUE;
// enter the "to do" loop while waiting for the timer...
While (dwKeepGoing)
{
switch (WaitForSingleObject(hTimer,0)
{
case WAIT_OBJECT_0:
// duration over,
// optionally finalize "to do" stuff here
// and end child
dwKeepGoing = FALSE;
case WAIT_TIMEOUT:
// do stuff here
break;
case WAIT_FAILED:
// the wait function has failed
printf("WaitForSingleObject failed (%d)\n", GetLastError());
return GetLastError();
}
}
return 0;
}
关于c++ - 我怎样才能产生一个只在给定时间内存在的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798854/