| 15 | #endif |
| 16 | |
| 17 | QStringList getProcessIdsByProcessName(const char *processName) |
| 18 | { |
| 19 | QStringList listOfPids; |
| 20 | |
| 21 | #if defined(WIN32) |
| 22 | // https://docs.microsoft.com/en-us/windows/win32/toolhelp/taking-a-snapshot-and-viewing-processes |
| 23 | /* Take a snapshot of all processes in the system */ |
| 24 | HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); |
| 25 | if(hProcessSnap == INVALID_HANDLE_VALUE) |
| 26 | { |
| 27 | return {}; |
| 28 | } |
| 29 | |
| 30 | PROCESSENTRY32W pe32{}; |
| 31 | pe32.dwSize = sizeof(PROCESSENTRY32W); |
| 32 | |
| 33 | /* Retrieve information about the first process */ |
| 34 | if(!Process32FirstW(hProcessSnap, &pe32)) |
| 35 | { |
| 36 | CloseHandle(hProcessSnap); |
| 37 | return {}; |
| 38 | } |
| 39 | |
| 40 | /* Walk through the snapshot of processes */ |
| 41 | do |
| 42 | { |
| 43 | if (QString::compare( processName, QString::fromWCharArray(pe32.szExeFile), Qt::CaseInsensitive) == 0) |
| 44 | listOfPids.append(QString::number(pe32.th32ProcessID)); |
| 45 | |
| 46 | } while(Process32NextW(hProcessSnap, &pe32)); |
| 47 | |
| 48 | CloseHandle(hProcessSnap); |
| 49 | |
| 50 | #else |
| 51 | |
| 52 | QDir dir("/proc"); |
| 53 | dir.setFilter(QDir::Dirs); |
| 54 | dir.setSorting(QDir::Name | QDir::Reversed); |
| 55 | |
| 56 | for (const QString & pid : dir.entryList()) { |
| 57 | QRegularExpression regexp("^\\d*$"); |
| 58 | if (!regexp.match(pid).hasMatch()) |
| 59 | { |
| 60 | /* Not a number, can not be PID */ |
| 61 | continue; |
| 62 | } |
| 63 | |
| 64 | QFile cmdline("/proc/" + pid + "/comm"); |
| 65 | if (!cmdline.open(QFile::ReadOnly | QFile::Text)) |
| 66 | { |
| 67 | /* Can not open cmdline file */ |
| 68 | continue; |
| 69 | } |
| 70 | |
| 71 | QTextStream in(&cmdline); |
| 72 | QString command = in.readAll(); |
| 73 | if (command.startsWith(processName)) |
| 74 | { |