最近在看到一个同事使用Qt编写的进程监控程序中使用taskkill命令根据进程名称来杀死进程, 关于taskkill命令的具体用法可以参考MSDN文档:taskkill
taskkill [/s <computer> [/u [<domain>\]<username> [/p [<password>]]]] {[/fi <filter>] [...] [/pid <processID> | /im <imagename>]} [/f] [/t]
参数 | 描述 |
---|---|
/s | Specifies the name or IP address of a remote computer (do not use backslashes). The default is the local computer. |
/u <username> | Runs the command with the account permissions of the user who is specified by or by <username>. The /u parameter can be specified only if /s is also specified. The default is the permissions of the user who is currently logged on to the computer that is issuing the command. |
/p | Specifies the password of the user account that is specified in the /u parameter. |
/fi | Applies a filter to select a set of tasks. You can use more than one filter or use the wildcard character (*) to specify all tasks or image names. The valid filters are listed in the Filter names, operators, and values section of this article. |
/pid | Specifies the process ID of the process to be terminated. |
/im | Specifies the image name of the process to be terminated. Use the wildcard character (*) to specify all image names. |
/f | Specifies that processes be forcefully ended. This parameter is ignored for remote processes; all remote processes are forcefully ended. |
/t | Ends the specified process and any child processes started by it. |
taskkill是Windows命令行里终止指定程序“进程”的命令。
/f 表示强制终止 /im 表示指定的进程名称,例如“explor.exe"
如果不使用名称,使用进程号,则用/PID,例如(假设已知道某进程的PID号是3352,PID号可以在windows任务管理器中查看): taskkill /f /pid 3352
使用场景:
会在开发定时脚本中用到,用于关闭进程;当然也可以用于进程监控程序的编写,例如如下的Qt代码片段:
void ProViewWidget::onBtnClicked()
{
// 处理启动和停止按钮事件
if (m_bRunning)
{
QFileInfo finfo(str2qstr(m_pcfg->exePath));
std::string temp = std::string("TASKKILL /F /IM ") + qstr2str(finfo.fileName());
//system(temp.c_str());
WinExec(temp.c_str(), 0);
if (m_pcfg->exePath.find("CD-IOT-MQ-Cli-") != m_pcfg->exePath.npos
|| m_pcfg->exePath.find("CD-IOT-Cli-") != m_pcfg->exePath.npos)
{
WinExec("TASKKILL /F /IM node.exe", 0);
}
}
else
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
char path[1000] = {NULL};
std::string strpath = m_pcfg->exePath;
strcpy(path, strpath.c_str());
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (!CreateProcessA(NULL, // No module name (use command line)
path, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
inputLineToEdit("进程启动失败!");
}
}
}