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
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
- The -o
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=
>> 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. Also, we learned how to customize the output generated by ps.