Serenity Operating System
at master 58 lines 1.7 kB view raw
1/* 2 * Copyright (c) 2021, Aziz Berkay Yesilyurt <abyesilyurt@gmail.com> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/QuickSort.h> 8#include <AK/Vector.h> 9#include <LibCore/ArgsParser.h> 10#include <LibCore/ProcessStatisticsReader.h> 11#include <LibCore/System.h> 12#include <LibMain/Main.h> 13#include <LibRegex/Regex.h> 14 15ErrorOr<int> serenity_main(Main::Arguments args) 16{ 17 TRY(Core::System::pledge("stdio rpath")); 18 TRY(Core::System::unveil("/sys/kernel/processes", "r")); 19 TRY(Core::System::unveil("/etc/passwd", "r")); 20 TRY(Core::System::unveil(nullptr, nullptr)); 21 22 bool case_insensitive = false; 23 bool invert_match = false; 24 StringView pattern; 25 26 Core::ArgsParser args_parser; 27 args_parser.add_option(case_insensitive, "Make matches case-insensitive", nullptr, 'i'); 28 args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v'); 29 args_parser.add_positional_argument(pattern, "Process name to search for", "process-name"); 30 args_parser.parse(args); 31 32 PosixOptions options {}; 33 if (case_insensitive) 34 options |= PosixFlags::Insensitive; 35 36 Regex<PosixExtended> re(pattern, options); 37 if (re.parser_result.error != regex::Error::NoError) { 38 return 1; 39 } 40 41 auto all_processes = TRY(Core::ProcessStatisticsReader::get_all()); 42 43 Vector<pid_t> matches; 44 for (auto& it : all_processes.processes) { 45 auto result = re.match(it.name, PosixFlags::Global); 46 if (result.success ^ invert_match) { 47 matches.append(it.pid); 48 } 49 } 50 51 quick_sort(matches); 52 53 for (auto& match : matches) { 54 outln("{}", match); 55 } 56 57 return 0; 58}