summaryrefslogtreecommitdiff
path: root/Userland/Utilities/pgrep.cpp
diff options
context:
space:
mode:
authorAziz Berkay Yesilyurt <abyesilyurt@gmail.com>2021-07-04 11:49:10 +0200
committerAndreas Kling <kling@serenityos.org>2021-07-04 14:27:47 +0200
commit11ff3c11f431bb872e4c07cfa178e80dfdf42279 (patch)
treecd6bd1aa3253ada7c192bbb4300b5a83df12edbb /Userland/Utilities/pgrep.cpp
parent3bbe86d8ead537385de97728d11104cf51d742f5 (diff)
downloadserenity-11ff3c11f431bb872e4c07cfa178e80dfdf42279.zip
Userland: Add pgrep
Diffstat (limited to 'Userland/Utilities/pgrep.cpp')
-rw-r--r--Userland/Utilities/pgrep.cpp58
1 files changed, 58 insertions, 0 deletions
diff --git a/Userland/Utilities/pgrep.cpp b/Userland/Utilities/pgrep.cpp
new file mode 100644
index 0000000000..abfdfa3884
--- /dev/null
+++ b/Userland/Utilities/pgrep.cpp
@@ -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;
+}