summaryrefslogtreecommitdiffhomepage
path: root/opentrack-compat/process-list.hpp
blob: a00cbb172bfdc1d8169dc49be944d9df05fdb296 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#pragma once

#include <QDebug>
#include <QStringList>

#if defined _WIN32

#include <windows.h>
#include <TlHelp32.h>

template<typename = void>
static QStringList get_all_executable_names()
{
    QStringList ret;
    HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (h == INVALID_HANDLE_VALUE)
        return ret;

    PROCESSENTRY32 e;
    e.dwSize = sizeof(e);

    if (Process32First(h, &e) != TRUE)
    {
        CloseHandle(h);
        return ret;
    }

    do {
        ret.append(e.szExeFile);
    } while (Process32Next(h, &e) == TRUE);

    CloseHandle(h);

    return ret;
}
#elif defined __APPLE__
#include <libproc.h>
#include <sys/param.h>
#include <cerrno>
#include <vector>

// link to libproc
template<typename = void>
static QStringList get_all_executable_names()
{
    QStringList ret;
    std::vector<int> vec;

    while (true)
    {
        int numproc = proc_listpids(PROC_ALL_PIDS, 0, nullptr, 0);
        if (numproc == -1)
        {
            qDebug() << "numproc failed" << errno;
            break;
        }
        vec.resize(numproc);
        int cnt = proc_listpids(PROC_ALL_PIDS, 0, &vec[0], sizeof(int) * numproc);
        if (cnt <= numproc)
        {
            char name[2 * 2 * MAXCOMLEN + 1];
            for (int i = 0; i < cnt; i++)
            {
                int ret = proc_name(vec[i], name, sizeof(name)-1);
                if (ret <= 0)
                    continue;
                name[ret] = '\0';
                ret.append(name);
            }
            return ret;
        }
    }
}

#elif defined __linux

// link to procps
#include <proc/readproc.h>
#include <cerrno>
template<typename = void>
static QStringList get_all_executable_names()
{
    QStringList ret;
    proc_t** procs = readproctab(PROC_FILLCOM);
    if (procs == nullptr)
    {
        qDebug() << "readproctab" << errno;
        return ret;
    }
    for (int i = 0; procs[i]; i++)
    {
        auto& proc = *procs[i];
        ret.append(proc.cmd);
    }
    freeproctab(procs);
    return ret;
}

#else
template<typename = void>
static QStringList get_all_executable_names()
{
    return QStringList();
}
#endif