Linux comes with a handful of monitoring tools which can help us to get some insight about the OS itself. The ps utility from the Procps package is one of those tools which can report some stats about the current processes in the OS.
In this tutorial, we're going to see how we can use the ps utility to find the uptime for a particular process.
2. Process Uptime
In order to see how long a particular Linux (or even Mac) process has been running, assuming that we already know the Process Id, we can enter the following command in our Bash shell:
>> ps -p <process_id> -o etime
Let's break down the command:
- ps helps us to see a snapshot of current processes in the operating system. ps stands for “Process Status”
- Using -p <process_id> option we can specify the process id. For example, -p20 or -p 20 are representing a process with 20 as the process id
- The -o <format> lets us specify a custom format for the output. That is, <format> is an argument in the form of a blank-separated or comma-separated list, which offers a way to specify individual output columns. Here we're justing going to know about the process elapsed time, so we're using the etime as the single output column. By the way, etime stands for “Elapsed Time”.
For example, if we run the above command for a process id of 1:
>> ps -p 1 -o etime
We would get the process's elapsed time:
This particular process has been running for 3 hours, 24 minutes and 30 seconds. In order to see the elapsed time in seconds, let's use etimes instead of etime:
>> ps -p 1 -o etimes ELAPSED 12270
Please note that we can't use the etimes option on a Mac.
3. Elapsed Output Format
By default, etime represents elapsed time since the process was started, in the [[DD-]hh:]mm:ss format. For example, for a process that has been running for 20 days, the elapsed time output would be something like:
The DD and hh parts are optional, so when the elapsed time is less than a day or less than an hour, they won't show up in the output:
This process has been running for 21 minutes and 51 seconds.
4. Custom Column Header
As we saw in the previous examples, the -o etime option prints the elapsed time under a column header named ELAPSED. We can rename this header using the -o etime=<header_name> syntax:
>> ps -p 1 -o etime=Uptime Uptime 03:24:30
Also, we can even remove the header altogether:
>> ps -p 1 -o etime= 03:24:30
Same is true for etimes:
>> ps -p 1 -o etimes= 12270
This comes in handy when we're going to write a script and we only care about the numerical output.
In this tutorial, we used the ps command-line utility to find out how long a particular process is running.
We also focused on and learned how to customize the output generated by ps.