c++clinuxprocess-management

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.


Solution

  • 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:

    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!