Get process uptime linux

How to find uptime of a linux process

As «uptime» has several meanings, here is a useful command.

ps -eo pid,comm,lstart,etime,time,args 

This command lists all processes with several different time-related columns. It has the following columns:

PID COMMAND STARTED ELAPSED TIME COMMAND 

PID = Process ID
first COMMAND = only the command name without options and without arguments
STARTED = the absolute time the process was started
ELAPSED = elapsed time since the process was started (wall clock time), format [[dd-]hh:]mm:ss TIME = cumulative CPU time, «[dd-]hh:mm:ss» format
second COMMAND = again the command, this time with all its provided options and arguments

If you have a limited version of ps such as is found in busybox , you can get the process start time by looking at the timestamp of /proc/ . For example, if the pid you want to look at is 55.

# ls -al /proc | grep 55 dr-xr-xr-x 7 root root 0 May 21 05:53 55 

. and then compare it with the current date.

# date Thu May 22 03:00:47 EDT 2014 

can generate the etimes= with proc entries like etime=$(date -d «$(stat -c %y /proc/$ | cut -d ‘ ‘ -f 1,2)» +%s); echo «$(date +%s) — $» | bc -l

1234 being the process id.

example with two processes started at the same hour minute seconds but not the same milliseconds:

$ stat /proc/9355 . Access: 2017-11-13 17:46:39.778791165 +0100 Modify: 2017-11-13 17:46:39.778791165 +0100 Change: 2017-11-13 17:46:39.778791165 +0100 $ stat /proc/9209 . Access: 2017-11-13 17:46:39.621790420 +0100 Modify: 2017-11-13 17:46:39.621790420 +0100 Change: 2017-11-13 17:46:39.621790420 +0100 

yes, too old and yet too hard stuff. I tried with the above proposed «stat» method but what if I had «touch»-ed the PID proc dir yesterday? This means my year-old process is shown with yesterday’s time stamp. Nah, not what I need 🙁

In the newer ones, it’s simple:

ps -o etimes -p ELAPSED 339521 

as simple as that. Time is present in seconds. Do whatever you need it for. With some older boxes, situation is harder, since there’s no etimes. One could rely on:

ps -o etime -p ELAPSED 76-03:26:15 

which look a «a bit» weird since it’s in dd-hh:mm:ss format. Not suitable for further calculation. I would have preferred it in seconds, hence I used this one:

ps -o etime -p --no-headers | awk -F '(:)|(-)' 'BEGIN;=1;i--) s=s+a[i]*$i>END' 339544 

do not parse the output of etime because busybox 1.29.3 changed the format. use the stat + /proc method instead

Such a simple thing is not properly answered after 5 years?

I don’t think you can accurately get milliseconds. eg. if you see man procfs and see /proc/$$/stat which has field 22 as startime, which is in «clock ticks», you would have something more precise, but clock ticks aren’t going at a perfectly constant rate (relative to ‘wall clock time’) and will be off. sleeping and certain things (ntpd I guess) offset it. For example on a machine running ntpd, with 8 days uptime and has never slept, dmesg -T has the same problem (I think. ), and you can see it here:

# date; echo h > /proc/sysrq-trigger; dmesg -T | tail -n1 ; date Fri Mar 3 10:26:17 CET 2017 [Fri Mar 3 10:26:16 2017] sysrq: SysRq : HELP : loglevel(0-9) reboot(b) crash(c) terminate-all-tasks(e) memory-full-oom-kill(f) kill-all-tasks(i) thaw-filesystems(j) sak(k) show-backtrace-all-active-cpus(l) show-memory-usage(m) nice-all-RT-tasks(n) poweroff(o) show-registers(p) show-all-timers(q) unraw(r) sync(s) show-task-states(t) unmount(u) force-fb(V) show-blocked-tasks(w) Fri Mar 3 10:26:17 CET 2017 
# example pid here is just your shell pid=$$ # current unix time (seconds since epoch [1970-01-01 00:00:00 UTC]) now=$(date +%s) # process start unix time (also seconds since epoch) # I'm fairly sure this is the right way to get the start time in a machine readable way (unlike ps). but could be wrong start=$(stat -c %Y /proc/"$pid") # simple subtraction (both are in UTC, so it works) age=$((now-start)) printf "that process has run for %s seconds\n" "$age" 

Источник

Читайте также:  Операционная система linux 64 разрядная

30 Useful ‘ps Command’ Examples for Linux Process Monitoring

ps (processes status) is a native Unix/Linux utility for viewing information concerning a selection of running processes on a system: it reads this information from the virtual files in the /proc filesystem. It is one of the important utilities for system administration specifically under process monitoring, to help you understand whats is going on in a Linux system.

It has numerous options for manipulating its output, however, you’ll find a small number of them practically useful for daily usage.

In this article, we’ll look at 30 useful examples of ps commands for monitoring active running processes on a Linux system.

Note that ps produces output with a heading line, which represents the meaning of each column of information, you can find the meaning of all the labels on the ps man page.

List All Processes in Current Shell

1. If you run the ps command without any arguments, it displays processes for the current shell.

List Current Running Processes

2. Display every active process on a Linux system in generic (Unix/Linux) format.

List Processes in Standard Format

3. Display all processes in BSD format.

List Processes in BSD Format

4. To perform a full-format listing, add the -f or -F flag.

List Processes in Long List Format

Display User Running Processes

5. You can select all processes owned by you (runner of the ps command, root in this case), type:

6. To display a user’s processes by real user ID (RUID) or name, use the -U flag.

$ ps -fU tecmint OR $ ps -fu 1000

List User Processes by ID

7. To select a user’s processes by effective user ID (EUID) or name, use the -u option.

$ ps -fu tecmint OR $ ps -fu 1000

8. The command below enables you to view every process running with root user privileges (real & effective ID) in user format.

Display Root User Running Processes

Display Group Processes

9. If you want to list all processes owned by a certain group (real group ID (RGID) or name), type.

$ ps -fG apache OR $ ps -fG 48

Display Group Processes

10. To list all processes owned by effective group name (or session), type.

Читайте также:  Linux dvd usb tool

Display Processes by PID and PPID

11. You can list processes by PID as follows.

List Processes by PID

12. To select process by PPID, type.

List Process by PPID

13. Make a selection using a PID list.

List Processes by PIDs

Display Processes by TTY

14. To select processes by tty, use the -t flag as follows.

$ ps -t pts/0 $ ps -t pts/1 $ ps -ft tty1

List Processes by TTY

15. A process tree shows how processes on the system are linked to each other; processes whose parents have been killed are adopted by the init (or systemd).

List Process Tree

16. You can also print a process tree for a given process like this.

$ ps -f --forest -C sshd OR $ ps -ef --forest | grep -v grep | grep sshd

List Tree View of Process

17. To print all threads of a process, use the -L flag, this will show the LWP (lightweight process) as well as NLWP (number of the lightweight processes) columns.

List Process Threads

Specify Custom Output Format

Using the -o or –format options, ps allows you to build user-defined output formats as shown below.

18. To list all format specifiers, include the L flag.

19. The command below allows you to view the PID, PPID, user name, and command of a process.

List Processes with Names

20. Below is another example of a custom output format showing file system group, nice value, start time, and elapsed time of a process.

$ ps -p 1154 -o pid,ppid,fgroup,ni,lstart,etime

List Process ID Information

Find Process using PID

Display Parent and Child Processes

22. To select a specific process by its name, use the -C flag, this will also display all its child processes.

Find Parent Child Process

23. Find all PIDs of all instances of a process, useful when writing scripts that need to read PIDs from an std output or file.

Find All Process PIDs

24. Check the execution time of a process.

$ ps -eo comm,etime,user | grep httpd

The output below shows the HTTPD service has been running for 1 hour, 48 minutes, and 17 seconds.

Find Process Uptime

Troubleshoot Linux System Performance

If your system isn’t working as it should be, for instance, if it’s unusually slow, you can perform some system troubleshooting as follows.

26. Find top running processes by highest memory and CPU usage in Linux.

$ ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head OR $ ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head

Find Top Running Processes

27. To kill Linux processes/unresponsive applications or any process that is consuming high CPU time.

First, find the PID of the unresponsive process or application.

Then use the kill command to terminate it immediately.

Find and Kill a Process

28. Show security context (specifically for SELinux) like this.

Find SELinux Context

29. You can also display security information in a user-defined format with this command.

$ ps -eo euser,ruser,suser,fuser,f,comm,label

List SELinux Context by Users

Perform Real-time Process Monitoring Using Watch Utility

30. Finally, since ps displays static information, you can employ the watch utility to perform real-time process monitoring with repetitive output, displayed after every second as in the command below (specify a custom ps command to achieve your objective).

$ watch -n 1 'ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head'

Real Time Process Monitoring

Important: ps only shows static information, to view frequently updated output you can use tools such as htop; top, and glances: the last two are in fact Linux system performance monitoring tools.

Читайте также:  Compare windows with linux

You might also like to read the following related articles.

That’s all for now. If you have any useful ps command example(s) to share (not forgetting to explain what it does), use the comment form below.

Источник

How to retrieve the process start time (or uptime) in python

How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call «ps -p my_process_id -f» and then parse the output. But it is not cool.

6 Answers 6

>>> import psutil, os, time >>> p = psutil.Process(os.getpid()) >>> p.create_time() 1293678383.0799999 >>> time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.create_time())) '2010-12-30 04:06:23' >>> 

. plus it’s cross platform, not only Linux.

NB: I am one of the authors of this project.

citing the FAQ ( stackoverflow.com/faq#promotion ) «you must disclose your affiliation in your answers.»

If you are doing it from within the python program you’re trying to measure, you could do something like this:

import time # at the beginning of the script startTime = time.time() # . def getUptime(): """ Returns the number of seconds since the program started. """ # do return startTime if you just want the process start time return time.time() - startTime 

Otherwise, you have no choice but to parse ps or go into /proc/pid . A nice bash y way of getting the elapsed time is:

ps -eo pid,etime | grep $YOUR_PID | awk '' 

This will only print the elapsed time in the following format, so it should be quite easy to parse:

(if it’s been running for less than a day, it’s just HH:MM:SS )

The start time is available like this:

ps -eo pid,stime | grep $YOUR_PID | awk '' 

Unfortunately, if your process didn’t start today, this will only give you the date that it started, rather than the time.

The best way of doing this is to get the elapsed time and the current time and just do a bit of math. The following is a python script that takes a PID as an argument and does the above for you, printing out the start date and time of the process:

import sys import datetime import time import subprocess # call like this: python startTime.py $PID pid = sys.argv[1] proc = subprocess.Popen(['ps','-eo','pid,etime'], stdout=subprocess.PIPE) # get data from stdout proc.wait() results = proc.stdout.readlines() # parse data (should only be one) for result in results: try: result.strip() if result.split()[0] == pid: pidInfo = result.split()[1] # stop after the first one we find break except IndexError: pass # ignore it else: # didn't find one print "Process PID", pid, "doesn't seem to exist!" sys.exit(0) pidInfo = [result.split()[1] for result in results if result.split()[0] == pid][0] pidInfo = pidInfo.partition("-") if pidInfo[1] == '-': # there is a day days = int(pidInfo[0]) rest = pidInfo[2].split(":") hours = int(rest[0]) minutes = int(rest[1]) seconds = int(rest[2]) else: days = 0 rest = pidInfo[0].split(":") if len(rest) == 3: hours = int(rest[0]) minutes = int(rest[1]) seconds = int(rest[2]) elif len(rest) == 2: hours = 0 minutes = int(rest[0]) seconds = int(rest[1]) else: hours = 0 minutes = 0 seconds = int(rest[0]) # get the start time secondsSinceStart = days*24*3600 + hours*3600 + minutes*60 + seconds # unix time (in seconds) of start startTime = time.time() - secondsSinceStart # final result print "Process started on", print datetime.datetime.fromtimestamp(startTime).strftime("%a %b %d at %I:%M:%S %p") 

Источник

Оцените статью
Adblock
detector