Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you get how long a process has been running?

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.

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

like image 858
kmdent Avatar asked Jun 28 '11 23:06

kmdent


1 Answers

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.

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

Obtaining these values:

  • 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).

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;

Happy Coding!

like image 125
kmdent Avatar answered Sep 20 '22 23:09

kmdent