从 linux "ps" 命令输出的 c# 中解析进程开始时间

Parsing process start time from linux "ps" command output in c#

如何解析 ps 命令的开始时间输出?如果它的形式是 06:38PM,它可以解析,但是当它看起来像 Tue01PM 时,它就不能解析了。我还尝试添加 cultureinfo,例如 Convert.ToDateTime(result[8], CultureInfo.GetCultureInfo("en-US")),并使用 ParseExact,例如 DateTime.ParseExact(result[8], "dddhhhh", CultureInfo.GetCultureInfo("en-US"))

在linux中,你可以override the system date format随便给它。然后你可以确定输出。那就是我会做的。

可以要求 ps 命令显示特定数据,在某些情况下以特定格式显示,这样可以更轻松地解析结果。您使用 -o 命令行选项请求特定数据,其参数是 comma-separated 形式的项目列表:item=HEADERHEADER 是要使用的列 header;省略它意味着不会为该列打印 header(但如果您也省略 =,您将获得默认值 header)。

开始时间至少有两个共同项:startlstart。这些分别为您提供了时间的标准版本和长版本:

$ ps -ostart= 2875
11:28:13
$ ps -olstart= 2875
Wed Mar 18 11:28:13 2015

在 Linux 上,ps 从 "file" /proc/<i>pid</i>/stat,这是包含 space-separated 个字段的单行(参见 man 5 proc)。开始时间是列表中的第 22 项;它是一个整数,表示自系统启动以来的时钟滴答数。在 bash 中,您可以通过一些工作将其转换为更有用的内容:

start_time() {
  local now running ticks uptime
  now=$(date +%s)            # time in seconds since epoch
  running=$(cut -d' ' -f22 /proc//stat)
                             # start time of process in ticks since boot
  ticks=$(getconf CLK_TCK)   # ticks per second (usually 100)
  uptime=($(</proc/uptime))  # seconds since boot and idle time
  bc <<<"$now-${uptime[0]}+$running/$ticks"
}

$ date +"%Y-%m-%d %H:%M:%S" -d@$(start_time 2875)
2015-03-18 11:28:12

给出 pid/进程 $MYPID 在 epoc 中的开始时间

MYPID=$PPID
STARTING_EPOC_OF_MYPID=$(date +%s -d "$(ps -olstart= ${MYPID})")
echo $STARTING_EPOC_OF_MYPID

我不太确定,如果这与上面不同。