检查使用 CreateProcess 执行的命令的返回值 [英] checking the return value of a command executed using CreateProcess

查看:54
本文介绍了检查使用 CreateProcess 执行的命令的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码使用 CreateProcess() api 执行taskkill"命令.

I am using the following code to execute 'taskkill' command using CreateProcess() api.

STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );

TCHAR cmd[] = TEXT("taskkill /F /T /IM <exe name>");

if (CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, & pi))
{
    // wait for child process to exit
    DWORD waitForStatus = WaitForSingleObject(pi.hProcess, 10000);

    // close process and thread handles
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    /* code to throw exception based on the return value waitForStatus */ 
}
else
{
   /* code to throw exception if CreateProcess() failed */
}

我观察到的是,如果进程没有运行,则任务终止会失败,但 CrateProcess() 不指示错误.如何从 CreateProcess 获取此错误?

What I observed is that if the process is not running, task kill fails, but CrateProcess() does not indicate the error. How to get this error from CreateProcess?

即使使用/F 开关,进程是否也不会被 taskkill 杀死?

Is there any possibilty that the process does not get killed by taskkill even with the /F switch?

推荐答案

CreateProcess 只负责生成/创建子流程(在您的情况下taskkill.exe) 成功,因此它返回 TRUE.您的代码有责任监视子流程以及何时结束以获取其退出代码.通过调用 [MS.Docs] 来做到这一点:关闭其句柄之前的 GetExitCodeProcess 函数:

CreateProcess is only responsible for spawning / creating the sub-process (in your case taskkill.exe) which is successful, therefore it returns TRUE. It's your code's responsibility to monitor the sub-process and when it ends to get its exit code. Do that by calling [MS.Docs]: GetExitCodeProcess function before closing its handle:

GetExitCodeProcess(pi.hProcess, &ec);

不要忘记先声明 ec (DWORD ec;).另外,反转句柄关闭的顺序(这不是强制性的,但逻辑上线程在其进程之前结束).

Don't forget to declare ec first (DWORD ec;). Also, reverse the order of handle closing (it's not mandatory, but logically a thread ends before its process).

这篇关于检查使用 CreateProcess 执行的命令的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆