If you've done Unix shell scripting of any kind, you're likely to recognize the `grep` command. `grep` will search through a source input (a file, files, recursive directories, or piped output) for lines that contain a specific string or regular expression.
What I often find myself doing is piping the output of `ps` to `grep`. `ps` gets a list of running processes. By passing the output of `ps` to `grep`, I can check for the existence of a running process. For example, if I want to know if Apache is running, I can execute `ps auwx | grep "apache"` and the output will show apache processes.
The trick with this is that it's not useful for automated scripts. The reason is that `ps` will always include the `ps` process itself. So if even Apache isn't running, there is always one line at the end of the `grep` that shows that I ran the `ps auwx | grep "apache"`.
The solution is to use `pgrep`, which is a grep for running processes. This avoids finding the command that executed the search in the first place, and only returns the process ids of the matching processes, one per line. As you can imagine, this is very useful if you want to write an automation script, because you don't have to deal with the extra process found on the end, and you can use the process ids as an argument to other tools, like `nice` or `kill`.
0 Responses to Finding Processes