pgrep: Add -l option to list the process name as well as its pid

This commit is contained in:
Tim Ledbetter 2023-05-30 17:51:22 +01:00 committed by Andreas Kling
parent ad851706ab
commit cb6a2d60d3
Notes: sideshowbarker 2024-07-17 03:03:44 +09:00
2 changed files with 14 additions and 8 deletions

View file

@ -5,7 +5,7 @@ pgrep - look up processes based on name
## Synopsis
```sh
$ pgrep [--count] [-d delimiter] [--ignore-case] [--invert-match] <process-name>
$ pgrep [--count] [-d delimiter] [--ignore-case] [--list-name] [--invert-match] <process-name>
```
## Options
@ -13,6 +13,7 @@ $ pgrep [--count] [-d delimiter] [--ignore-case] [--invert-match] <process-name>
* `-c`, `--count`: Suppress normal output and print the number of matching processes
* `-d`, `--delimiter`: Set the string used to delimit multiple pids
* `-i`, `--ignore-case`: Make matches case-insensitive
* `-l`, `--list-name`: List the process name in addition to its pid
* `-v`, `--invert-match`: Select non-matching lines
## Arguments

View file

@ -23,6 +23,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
bool display_number_of_matches = false;
auto pid_delimiter = "\n"sv;
bool case_insensitive = false;
bool list_process_name = false;
bool invert_match = false;
StringView pattern;
@ -30,6 +31,7 @@ ErrorOr<int> serenity_main(Main::Arguments args)
args_parser.add_option(display_number_of_matches, "Suppress normal output and print the number of matching processes", "count", 'c');
args_parser.add_option(pid_delimiter, "Set the string used to delimit multiple pids", "delimiter", 'd', nullptr);
args_parser.add_option(case_insensitive, "Make matches case-insensitive", "ignore-case", 'i');
args_parser.add_option(list_process_name, "List the process name in addition to its pid", "list-name", 'l');
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(args);
@ -45,24 +47,27 @@ ErrorOr<int> serenity_main(Main::Arguments args)
auto all_processes = TRY(Core::ProcessStatisticsReader::get_all());
Vector<pid_t> matches;
for (auto& it : all_processes.processes) {
Vector<Core::ProcessStatistics> matches;
for (auto const& it : all_processes.processes) {
auto result = re.match(it.name, PosixFlags::Global);
if (result.success ^ invert_match) {
matches.append(it.pid);
matches.append(it);
}
}
if (display_number_of_matches) {
outln("{}", matches.size());
} else {
quick_sort(matches);
quick_sort(matches, [](auto const& a, auto const& b) { return a.pid < b.pid; });
auto displayed_at_least_one = false;
for (auto& match : matches) {
if (displayed_at_least_one)
out("{}{}"sv, pid_delimiter, match);
else
out("{}"sv, match);
out("{}"sv, pid_delimiter);
out("{}"sv, match.pid);
if (list_process_name)
out(" {}"sv, match.name);
displayed_at_least_one = true;
}