4

I need to get the start time of process using C code in userspace.
The process will run as root, So I can fopen /proc/PID/stat.
I saw implementation, e.g:

start time of a process on linux
or
http://brokestream.com/procstat.c

But they are invalid, Why they are invalid ? if the process 2nd parameter contains space, e.g:

[ilan@CentOS7286-64 tester]$ cat /proc/1077/stat
1077 (rs:main Q:Reg) S 1 1054 1054 0 -1 1077944384 21791 0 10 0 528 464 0 0 20 0 3 0 1056 321650688 1481 18446744073709551615 1 1 0 0 0 0 2146172671 16781830 1133601 18446744073709551615 0 0 -1 1 0 0 1 0 0 0 0 0 0 0 0 0 0

These solutions will not work.

Is there a better way retrieving a process start time other then parsing the /proc/PID/stat results ? I can do the following logic:

  1. read long, first parameter is pid
  2. read char, make sure that i finish reading only when hitting close ')'. - 2nd parameter is tcomm (filename of the executable)
  3. read char - 3rd parameter process state.

In solaris, you simply read the result to psinfo_t struct.

ilansch
  • 4,784
  • 7
  • 47
  • 96
  • Perhaps you want something like this : https://stackoverflow.com/questions/5828753/start-time-of-a-process-on-linux?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – schaiba Jun 11 '18 at 06:25
  • Hi, Read the questions again :) I put that solution as invalid answer. – ilansch Jun 11 '18 at 06:26
  • 1
    Your procedure is incorrect. You use [`getline()`](http://man7.org/linux/man-pages/man3/getline.3.html) to read the entire line. First int is a pid. The second field begins after the first `(` in the line, and ends before the last `)` in the line. You can use e.g. [`strchr(line, '(')`](http://man7.org/linux/man-pages/man3/strchr.3.html) and [`strrchr(line, ')')`](http://man7.org/linux/man-pages/man3/strrchr.3.html) to find the parens. The fields in `/proc/PID/stat` are listed at [`man 5 proc`](http://man7.org/linux/man-pages/man5/proc.5.html). – Nominal Animal Jun 11 '18 at 10:38

1 Answers1

5

You can simply use the stat(2) kernel call.

The creation time is not set by the proc file system. But you can use the modification time, because the modification time of a directory changes only, if files are added to or removed from the directory. And because the content of a directory in the proc filesystem changes only, if you replace the kernel module of the running kernel, you can be pretty sure, that the modification time is also the creation time.

Example:

$ stat -c %y /proc/1
2018-06-01 11:46:57.512000000 +0200
$ uptime -s
2018-06-01 11:46:57
ceving
  • 21,900
  • 13
  • 104
  • 178