mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 18:07:34 +00:00
Userland: Add pgrep
This commit is contained in:
parent
3bbe86d8ea
commit
11ff3c11f4
2 changed files with 60 additions and 1 deletions
58
Userland/Utilities/pgrep.cpp
Normal file
58
Userland/Utilities/pgrep.cpp
Normal file
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* 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 processes = Core::ProcessStatisticsReader::get_all();
|
||||
if (!processes.has_value())
|
||||
return 1;
|
||||
|
||||
Vector<pid_t> matches;
|
||||
for (auto& it : processes.value()) {
|
||||
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;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue