Linux process create time

How to get the start time of a long-running Linux process?

Is it possible to get the start time of an old running process? It seems that ps will report the date (not the time) if it wasn’t started today, and only the year if it wasn’t started this year. Is the precision lost forever for old processes?

Is there anything wrong with using ps -p -o lstart ? Seems like it works, but I’m not sure why it’s not the immediate obvious answer for the many times this question seems to come up.

@ajwood It would be better to use ps -p -o lstart= to avoid additional line (header) to be printed.

Is there anything wrong with using ps -p -o lstart ? Maybe the fact there’s no lstart neither in 2004 Edition nor in 2013 Edition of POSIX 1003.1 standard?

@PiotrDobrogost, that would be a problem if the question asked about POSIX, but it’s asking about Linux.

Mods — techraf, Makyen, David Rawson, Tsyvarev, Paul Roub — why don’t you move it to a more appropriate site such as StackExchange or Superuser instead of closing the question? This is a good and useful question

8 Answers 8

You can specify a formatter and use lstart , like this command:

The above command will output all processes, with formatters to get PID, command run, and date+time started.

Example (from Debian/Jessie command line)

$ ps -eo pid,lstart,cmd PID CMD STARTED 1 Tue Jun 7 01:29:38 2016 /sbin/init 2 Tue Jun 7 01:29:38 2016 [kthreadd] 3 Tue Jun 7 01:29:38 2016 [ksoftirqd/0] 5 Tue Jun 7 01:29:38 2016 [kworker/0:0H] 7 Tue Jun 7 01:29:38 2016 [rcu_sched] 8 Tue Jun 7 01:29:38 2016 [rcu_bh] 9 Tue Jun 7 01:29:38 2016 [migration/0] 10 Tue Jun 7 01:29:38 2016 [kdevtmpfs] 11 Tue Jun 7 01:29:38 2016 [netns] 277 Tue Jun 7 01:29:38 2016 [writeback] 279 Tue Jun 7 01:29:38 2016 [crypto] . 

You can read ps ‘s manpage or check Opengroup’s page for the other formatters.

Be aware that lstart time can change, the stat methods below are safer — unix.stackexchange.com/questions/274610/….

The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart which always gives the full date and time the process started:

# ps -p 1 -wo pid,lstart,cmd PID STARTED CMD 1 Mon Dec 23 00:31:43 2013 /sbin/init # ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd USER PID %CPU %MEM VSZ RSS TT STAT STARTED CMD root 1 0.0 0.1 2800 1152 ? Ss Mon Dec 23 00:31:44 2013 /sbin/init root 5151 0.3 0.1 4732 1980 pts/2 S Sat Mar 8 16:50:47 2014 bash 

(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:

# date; ls -ld /proc/1 /proc/$$ Sat Mar 8 17:14:21 EST 2014 dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1 dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151 

Note that in this case I ran a «ps -p 1» command at about 16:50, then spawned a new bash shell, then ran the «ps -p 1 -p $$» command within that shell shortly afterward. )

Читайте также:  Установка линукс разбивка дисков

Источник

Linux Commando

Initially a Linux command-line interface blog, it has evolved to cover increasingly more GUI app topics. Instead of just giving you information like some man page, I illustrate their usage in real-life scenarios.

Search This Blog

Sunday, September 21, 2008

How to get the process start date and time

How can we determine when a running process was started?

The venerable ps command deserves first consideration.

Most Linux command-line users are familiar with either the standard UNIX notation or the BSD notation when it comes to specifying ps options.

If ps -ef is what you use, that is the UNIX notation.

$ ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 Sep20 ? 00:00:03 init [3]

peter 1218 1 0 Sep20 ? 00:21:35 /usr/lib/iceweasel/firefox-bin -a firefox

peter 4901 1 1 16:34 ? 00:01:12 /usr/bin/emacs-snapshot-gtk

The STIME column displays the start time or date. From the above, we can tell that process 4901 (emacs) began execution at 16:34 (4:34 pm). But on what day, today?

From the ps man page: ‘Only the year will be displayed if the process was not started the same year ps was invoked, or «mmmdd» if it was not started the same day, or «HH:MM» otherwise.’

So, emacs was started at 16:34 TODAY.

What is the start time for the other process, the firefox process with pid 1218?

The STIME for process 1218 reads Sep20 (which was yesterday). But what time yesterday?

The default ps -ef only tells you the start date but NOT the time if a process was NOT started on the same day.

If the BSD notation is more familiar to you, you will find that ps aux yields similar results.

$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 1576 540 ? Ss Sep20 0:03 init[3]

peter 1218 0.5 8.9 201252 45456 ? Sl Sep20 21:35 /usr/lib/iceweasel/firefox-bin -a firefox

The Start column in the above output only reveals the start date if the process is older than the current day.

There are (at least) 2 ways to determine the exact start time if the process was started before the current day.

Solution 1
Specify elapsed time in the ps output format.

$ ps -eo pid,cmd,etime 
PID CMD ELAPSED
1218 /usr/lib/iceweasel/firefox-bin - 2-16:04:45

The above ps command specifies 3 fields to be included in the output: the process pid, the command, and the elapsed time, respectively.

etime is the elapsed time since the process was started, in the form dd-hh:mm:ss. dd is the number of days; hh , the number of hours; mm , the number of minutes; ss , the number of seconds.

The firefox command started execution 2 days, 16 hours, 4 minutes and 45 seconds ago. To find the exact time, you need to do some simple math.

If you prefer the BSD notation, issue this command:

$ ps axo pid,cmd,etime 
PID CMD ELAPSED

1218 /usr/lib/iceweasel/firefox-bin - 2-16:04:57

Solution 2
Get the process pid and read off the timestamp in the corresponding subdirectory in /proc .

Читайте также:  Astra linux repository smolensk

First, get the process pid using the ps command ( ps -ef or ps aux )

Then, use the ls command to display the creation timestamp of the directory.

$ ls -ld /proc/1218
dr-xr-xr-x 5 peter peter 0 Sep 20 16:14 /proc/1218

You can tell from the timestamp that the process 1218 began executing on Sept 20, 16:14.

If you can think of another clever way to get the start time and date, please let us know.

18 comments:

This post was really useful to me.
Thanks for sharing your knowledge.

another simple way to know process start time:

Looking at the mtime of /proc/PID may not yield useful results. For example on my PC most entries changed their time today at 19:29 for some reason.
But using the elapsed time still works — or the lstart format option to ps as sujeet suggested.

If you want the timestamp :

date -d «`ps -p __PID__ -o lstart=`» +’%s’

another simple way to know process start time:

lol! indeed sujeet suggestion is complete and excelent! look at this output:

ps -eo pid,lstart,cmd | grep ps
1418 Mon Jun 1 15:49:19 2009 [khpsbpkt]
1454 Mon Jun 1 15:49:19 2009 [kpsmoused]
12547 Mon Jun 1 15:50:02 2009 dcopserver [kdeinit] —nosid
16642 Sun Jun 7 03:50:58 2009 ps -eo pid,lstart,cmd
16643 Sun Jun 7 03:50:58 2009 grep —colour=auto ps

actually, using ‘ps’ on linux is not always reliable. i’ve seen situations where ‘ps’ can return different start time for a given process with subsequent invocations. the difference is usually 1 second (probably a rounding error). it’s more reliable to use

proc /proc//stat | awk »
this will give start time in jiffies since last system reboot.

The process start time drift you’ve seen in ps is probably related to this:
https://bugzilla.redhat.com/show_bug.cgi?id=518730

Due to the way that the start time of a process is calculated by ps (/proc/stat btime + /proc/PID/stat jiffies since process start) when NTP adjusts the system clock forward over time the start time of long running processes drifts.

The timestamp of the /proc/pid file is changed under certain conditions. Example: using Ubuntu 10.4 the timestamps are updated once a day by some cron job. It’s possible to change the timestamp by just ‘touching’ the directory.

i want to display the process created date & time only in Unix ?

Anyone Know Just Give post your answer

Great post. Thanks especially for the /proc/pid

Great post , It really helped me , thank you

Great bro, your post helped me

Thank you sooo much for this informative post.

You can achieve the same with: ps axo pid,user,cmd,lstart

Thank you for this post, I’ve got what I needed, but Solution #2 is not a solution actually, because it sometimes gives wrong results:

$ ls -ld —full-time /proc/23555
dr-xr-xr-x 8 irv tenso 0 2016-02-04 12:00:55.005137889 +0300 /proc/23555/
$ ps -eo pid,lstart,cmd | grep 23555
23555 Thu Feb 4 12:00:00 2016 ffmpeg -i rtsp://10.2.8.2:554/axis-media/media.amp -r 30 -c copy -t 3616 -strftime 1 video//10.2.8.2_2016.02.04_12:00:00.mp4

I suggest you to remove it.

The solution with the proc directory is wrong because it’s updated frequently.

You can calculate the start time by the (already mentioned) jiffies since boot time.
If you want an easy-to-use binary for this purpose you can use «lps» of the package ngtx:
http://www.tuxad.com/download-ngtx.html

Читайте также:  Установка wine через терминал linux mint

lps prints the «age» of processes at the start of the line to give you the ability of using «sort -n» to order processes by «age».

Thanks for the topic. very much useful for beginners..
i used this commands in my development phase. after reading this.

Cool info! Too bad elapsed isn’t a default column . nice!

Источник

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