您如何获得一个进程运行了多长时间?

kmd*_*ent 5 c c++ linux process-management

有没有办法从/proc目录中获取此信息?我希望能够获得每个进程在几秒钟内已经运行了多长时间。

编辑:我需要从C ++做到这一点。对困惑感到抱歉。

kmd*_*ent 6

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

Process_Time = (current_time - boot_time) - (process_start_time)/HZ.
Run Code Online (Sandbox Code Playgroud)

(您必须除以HZ,因为process_start_time在抖动中)

获得这些值:

  • current_time-您可以从C命令中获取gettimeofday()
  • boot_time-此值位于中/proc/uptime。该文件包含两个数字:系统的正常运行时间(秒)和空闲过程中花费的时间量(秒)。先走
  • process_start_time-此值位于中/proc/[PID]/stat。系统启动与进程启动之间的时间差(以分钟为单位)。(如果在空白处分割,则文件中的第22个值)。

代码(对不起,我有时会混合使用c和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;
Run Code Online (Sandbox Code Playgroud)

编码愉快!