简体   繁体   English

Linux获取给定PID的进程开始时间

[英]Linux get process start time of given PID

I need to get the start time of process using C code in userspace. 我需要在用户空间中使用C代码获取进程的开始时间。
The process will run as root, So I can fopen /proc/PID/stat. 该进程将以root身份运行,因此我可以fopen / proc / PID / stat。
I saw implementation, eg: 我看到了实施,例如:

start time of a process on linux 在linux上启动进程的时间
or 要么
http://brokestream.com/procstat.c http://brokestream.com/procstat.c

But they are invalid, Why they are invalid ? 但它们无效,为什么它们无效? if the process 2nd parameter contains space, eg: 如果进程第二个参数包含空格,例如:

[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 ? 除了解析/ proc / PID / stat结果之外,还有更好的方法来检索进程启动时间吗? I can do the following logic: 我可以做以下逻辑:

  1. read long, first parameter is pid 读长,第一个参数是pid
  2. read char, make sure that i finish reading only when hitting close ')'. 读取字符,确保只有在按下')'才能完成阅读。 - 2nd parameter is tcomm (filename of the executable) - 第二个参数是tcomm(可执行文件的文件名)
  3. read char - 3rd parameter process state. read char - 第三个参数进程状态。

In solaris , you simply read the result to psinfo_t struct. solaris中 ,您只需将结果读取到psinfo_t结构。

You can simply use the stat(2) kernel call. 您只需使用stat(2)内核调用即可。

The creation time is not set by the proc file system. proc文件系统不设置创建时间。 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. 并且因为proc文件系统中目录的内容只是更改,如果替换正在运行的内核的内核模块,您可以非常肯定,修改时间也是创建时间。

Example: 例:

$ stat -c %y /proc/1
2018-06-01 11:46:57.512000000 +0200
$ uptime -s
2018-06-01 11:46:57

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM