Is there a way to get this information from the /proc
directory? I want to be able to get how long each process has been running on seconds.
EDIT: I needed to do this from C++. Sorry for the confusion.
Is there a way to get this information from the /proc
directory? I want to be able to get how long each process has been running on seconds.
EDIT: I needed to do this from C++. Sorry for the confusion.
But why not just read /proc/{processid}/stat, and simply get whatever statistics you want?
from "man proc":
...
Let's break down what you're trying to do:
So, in order to get the current time, we can run:
Now, the next step is parsing it to Unix time -- but we don't have to! The %X specifier actually converts it to Unix Time. So next step would be to (a) get the current time (b) subtract the times:
So yeah, that's pretty much it. The pipe is needed to get the input from one to the other.
The time command will give you that info:
Command-line arguments will make it return
You can call
system( char *command )
to execute the command from your prog.You can do
stat /proc/{processid}
to see the creation time at the shell.EDIT: fstat on that folder should give you what you want (the creation time).
Okay guys, so after reading the
top
command's source code, I figured out a non-hacky way of getting the start time of a process. The formula that they use is:(You have to divide by HZ because process_start_time is in jiffies)
Obtaining these values:
current_time
- You can get this from the C commandgettimeofday()
.boot_time
- This value is located in/proc/uptime
. This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds). Take the first.process_start_time
- This value is located in/proc/[PID]/stat
. The time difference (in jiffies) between system boot and when the process started. (The 22nd value in the file if you split on whitespace).The code (Sorry, I sometimes mix c and c++):
Happy Coding!
Old topic this, but since I was working on the same issues, I thought I might post my response. Perhaps it would be useful for someone else. Note, this code should not be used in a serious production environment, but as a quick and dirty way to get what the OP is looking for, I think this would be sufficient. Note that this code is the same code as OP posted in response to his own question, but it is modified to be able to be directly compiled when you copy it from stackexchange, his code was not directly able to compile.
This code compile, and I've added a few extra functions.
Instructions: Start any program, then do a 'ps aux | programname' to get its pid. It's the second column from the left. Now input that number to pid in the main function and compile the program. Now, when running the program, the output will be something like:
Lapsed: days: 0 , hours: 0 , min: 5 , seconds: 58