您如何获得一个进程已经运行了多长时间? [英] how do you get how long a process has been running?

查看:126
本文介绍了您如何获得一个进程已经运行了多长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从/proc目录获取此信息?我希望能够获得每个进程运行几秒钟的时间.

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.

我需要从C ++做到这一点.抱歉造成混乱.

I needed to do this from C++. Sorry for the confusion.

推荐答案

好的,所以,在阅读top命令的源代码之后,我想出了一种获取过程开始时间的简便方法.他们使用的公式是:

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:

Process_Time = (current_time - boot_time) - (process_start_time)/HZ.

(您必须除以HZ,因为process_start_time处于jiffies之内)

(You have to divide by HZ because process_start_time is in jiffies)

获得这些值:

  • current_time-您可以从C命令gettimeofday()中获取.
  • boot_time-此值位于/proc/uptime中.该文件包含两个数字:系统的正常运行时间(秒)和空闲过程中花费的时间量(秒).拿第一个.
  • process_start_time-此值位于/proc/[PID]/stat中.系统启动与进程启动之间的时间差(以分钟为单位). (如果在空白处分割,则文件中的第22个值).
  • current_time - You can get this from the C command gettimeofday().
  • 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).

代码(对不起,我有时会混合使用c和c ++):

The code (Sorry, I sometimes mix c and c++):

  int fd;
  char buff[128];
  char *p;
  unsigned long uptime;
  struct timeval tv;
  static time_t boottime;


  if ((fd = open("/proc/uptime", 0)) != -1)
  {
    if (read(fd, buff, sizeof(buff)) > 0)
    {
      uptime = strtoul(buff, &p, 10);
      gettimeofday(&tv, 0);
      boottime = tv.tv_sec - uptime;

    }
    close(fd);
  }


ifstream procFile;
procFile.open("/proc/[INSERT PID HERE]/stat");

char str[255];
procFile.getline(str, 255);  // delim defaults to '\n'


vector<string> tmp;
istringstream iss(str);
copy(istream_iterator<string>(iss),
     istream_iterator<string>(),
     back_inserter<vector<string> >(tmp));

process_time = (now - boottime) - (atof(tmp.at(21).c_str()))/HZ;

快乐编码!

这篇关于您如何获得一个进程已经运行了多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆