Kill process without knowing the full path using Qt
I'm trying to retrieve the active processes on my computer and to search for specific one, if it exists then i should 开发者_高级运维kill it. Is it possible to do it without knowing the specific path of the execute? I know the execute process name but not the full path.
So in short:
- Get all active processes.
- Kill specific process.
Thanks!
AFAIK there is no Qt-specific way to do what you want, so you have to use native platform API. Which platform (Widnows, Unix, MacOS) are you interested in?
EDIT: Take a look at MSDN process functions reference: http://msdn.microsoft.com/en-us/library/ms684847(v=VS.85).aspx , especially EnumProcesses, OpenProcess and TerminateProcess. I won't give you any code snippets, since I haven't used this API myself (I just have it bookmarked).
like it was said, you could do it for windows relatively easy using win api: Enumerating All Processes && Terminating a Process
for linux you could try running smth like "ps -A" using QProcess and parse its standard output; smth like this:
QProcess process;
process.setProcessChannelMode(QProcess::MergedChannels);
process.start("ps", QStringList() << "-A");
if (!process.waitForStarted())
return;
if (!process.waitForFinished())
return;
//qDebug() << process.readAll();
QByteArray output = process.readLine().trimmed();
while (!output.isEmpty())
{
qDebug() << output;
QList<QByteArray> items = output.split(' ');
qDebug() << "pid:" << items.first() << " cmd:" << items.last();
qDebug() << "===============================================";
output = process.readLine().trimmed();
}
this should return a list of running processes, you could try different command line options for ps to get the data you need. I believe killing the process could be done the same ways; by running kill [pid]
hope this would give you an idea on how to proceed, regards
If you are on MacOS or BSD you can list all the processes using the sysctl API.
On Linux it seems the best you can do is look at how it's done in the source code to ps, which is basically to navigate the /proc
file system.
精彩评论