ladybird/Userland/Utilities/pgrep.cpp
Tom 7e77a2ec40 Everywhere: Improve CPU usage calculation
As threads come and go, we can't simply account for how many time
slices the threads at any given point may have been using. We need to
also account for threads that have since disappeared. This means we
also need to track how many time slices we have expired globally.

However, because this doesn't account for context switches outside of
the system timer tick values may still be under-reported. To solve this
we will need to track more accurate time information on each context
switch.

This also fixes top's cpu usage calculation which was still based on
the number of context switches.

Fixes #6473
2021-07-18 22:08:26 +02:00

58 lines
1.5 KiB
C++

/*
* Copyright (c) 2021, Aziz Berkay Yesilyurt <abyesilyurt@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/QuickSort.h>
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/ProcessStatisticsReader.h>
#include <LibRegex/Regex.h>
int main(int argc, char** argv)
{
if (pledge("stdio rpath", nullptr) < 0) {
perror("pledge");
return 1;
}
bool case_insensitive = false;
bool invert_match = false;
char const* pattern = nullptr;
Core::ArgsParser args_parser;
args_parser.add_option(case_insensitive, "Make matches case-insensitive", nullptr, 'i');
args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v');
args_parser.add_positional_argument(pattern, "Process name to search for", "process-name");
args_parser.parse(argc, argv);
PosixOptions options {};
if (case_insensitive)
options |= PosixFlags::Insensitive;
Regex<PosixExtended> re(pattern, options);
if (re.parser_result.error != Error::NoError) {
return 1;
}
auto all_processes = Core::ProcessStatisticsReader::get_all();
if (!all_processes.has_value())
return 1;
Vector<pid_t> matches;
for (auto& it : all_processes.value().processes) {
auto result = re.match(it.name, PosixFlags::Global);
if (result.success ^ invert_match) {
matches.append(it.pid);
}
}
quick_sort(matches);
for (auto& match : matches) {
outln("{}", match);
}
return 0;
}