C++ 如何获得进程已运行的时间?

C++ 如何获得进程已运行的时间?,c++,c,linux,process-management,C++,C,Linux,Process Management,有没有办法从/proc目录中获取此信息?我希望能够得到每个进程在几秒钟内运行的时间 编辑:我需要从C++中做这件事。很抱歉造成混淆。您可以执行stat/proc/{processid}查看shell的创建时间 编辑:在该文件夹上,应该提供您想要的信息(创建时间)。时间命令将提供该信息: > man 1 time 命令行参数将使其返回 %S Total number of CPU-seconds that the process spent in kernel mode.

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


编辑:我需要从C++中做这件事。很抱歉造成混淆。

您可以执行
stat/proc/{processid}
查看shell的创建时间


编辑:在该文件夹上,应该提供您想要的信息(创建时间)。

时间命令将提供该信息:

> man 1 time
命令行参数将使其返回

%S     Total number of CPU-seconds that the  process  spent  in  kernel mode.
%U     Total number of CPU-seconds that the process spent in user mode.
%P     Percentage of the CPU that this job got

您可以调用
system(char*command)
来执行程序中的命令。

让我们来分析一下您试图执行的操作:

  • 获取文件被修改的时间
  • 将时间转换为Unix时间
  • 减去两次
  • 因此,为了获得当前时间,我们可以运行:

    #include <cstdio>
    #include <cstdlib>
    char *command;
    int process_number = 1; // init process.
    SYSTEM ("mkfifo time_pipe");
    sprintf (command, "stat /proc/%d -printf="%%X" > time_pipe", process_number); // get the command to run.
    // since this directory is created once it starts, we know it is the start time (about)
    // note the %%, which means to print a literal %
    SYSTEM (command); // run the command.
    

    是的,差不多就是这样。需要管道来获取从一个到另一个的输入。

    好了,伙计们,所以在阅读了
    top
    命令的源代码后,我找到了一种获取进程开始时间的非黑客方法。他们使用的公式是:

    Process_Time = (current_time - boot_time) - (process_start_time)/HZ.
    
    (您必须除以HZ,因为进程的开始时间是以jiffies为单位的)

    获取这些值:

    • current\u time
      -您可以通过C命令
      gettimeofday()
      获取此信息
    • boot\u time
      -此值位于
      /proc/uptime
      中。此文件包含两个数字:系统的正常运行时间(秒)和空闲进程所花费的时间(秒)。以第一个为例
    • process\u start\u time
      -此值位于
      /proc/[PID]/stat
      中。系统启动和进程启动之间的时间差(单位:秒)。(如果按空格分割,则为文件中的第22个值)
    代码(对不起,我有时混合使用c和c++):

    intfd;
    字符buff[128];
    char*p;
    未签名的长正常运行时间;
    结构时间值电视;
    静态时间\u t引导时间;
    如果((fd=open(“/proc/uptime”,0))!=-1)
    {
    如果(读取(fd、buff、sizeof(buff))>0)
    {
    正常运行时间=strtoul(buff,&p,10);
    gettimeofday(&tv,0);
    开机时间=tv.tv_秒-正常运行时间;
    }
    关闭(fd);
    }
    ifstream文件;
    open(“/proc/[INSERT PID HERE]/stat”);
    char-str[255];
    procFile.getline(str,255);//delim默认为“\n”
    向量tmp;
    istringstream iss(str);
    复制(istream_迭代器(iss),
    istream_迭代器(),
    背部插入器(tmp);
    进程时间=(现在-启动时间)-(atof(tmp.at(21).c_str())/HZ;
    
    快乐编码

    /proc/{processid}#好主意

    但是为什么不直接读取/proc/{processid}/stat,然后简单地获取您想要的任何统计数据呢

    从“人的过程”:

    
    

    这是一个老话题,但由于我正在处理相同的问题,我想我可能会发布我的回复。也许它对其他人有用。注意,这段代码不应该在严肃的生产环境中使用,但是作为一种快速而肮脏的方式来获取OP所寻找的内容,我认为这就足够了。请注意,此代码与OP在回答他自己的问题时发布的代码相同,但经过修改,可以在从stackexchange复制时直接编译,而他的代码无法直接编译

    这段代码可以编译,我还添加了一些额外的函数

    说明:启动任何程序,然后执行“ps aux | programname”以获取其pid。这是左边的第二列。现在,在主函数中将该数字输入pid并编译程序。现在,当运行程序时,输出将如下所示:

    失效时间:天:0小时:0分钟:5秒:58

    //kmdent提供的原始代码贷记。
    //http://stackoverflow.com/questions/6514378/how-do-you-get-how-long-a-process-has-been-running
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #包括
    #include“/usr/include/x86_64-linux-gnu/sys/param.h”
    使用名称空间std;
    模板
    内联标准::字符串到_字符串(常量T&T)
    {
    std::stringstream-ss;
    ss(0){
    正常运行时间=strtoul(buff,&p,10);
    gettimeofday(&tv,0);
    开机时间=tv.tv_秒-正常运行时间;
    }
    关闭(fd);
    }
    ifstream文件;
    字符串f=“/proc/”+pid+“/stat”;
    procFile.open(f.c_str());
    char-str[255];
    procFile.getline(str,255);//delim默认为“\n”
    向量tmp;
    istringstream iss(str);
    复制(istream_迭代器(iss),
    istream_迭代器(),
    背部插入器(tmp);
    std::time\u t now=std::time(0);
    std::time_t lassed=(现在是引导时间)-(atof(tmp.at(21.c_str())/HZ);
    返回失效;
    }
    字符串人类可读性失效(长输入秒){
    //学分:http://www.cplusplus.com/forum/beginner/14357/
    长天数=输入秒/60/60/24;
    整小时=(输入秒/60/60)%24;
    整数分钟=(输入秒/60)%60;
    整数秒=输入秒数%60;
    返回“天:“+到字符串(天)+”,小时:“+到字符串(小时)+”,分钟:“+到字符串(分钟)+”,秒:“+到字符串(秒)”;
    }
    int main(int argc,char*argv[])
    {
    //获取的总运行时间的Pid。
    字符串pid=“13875”;
    
    std::打电话很好。我不想检查文件夹是什么时候创建的。谢谢!我认为它不会给你文件夹创建时间。它会给你更改时间、修改时间和访问时间。这些都不会给你文件夹创建的时间。@kmdent:默认情况下,你不会得到创建时间,因为不是所有的文件系统都支持它,但请参阅以获取详细信息给你创建时间的潜在解决方案。修改时间与创建时间不同。Stat提供修改时间、访问时间和更改时间。这实际上不会给你流程创建时间。你同意吗?@kmdent是的,你似乎是对的。我想另一种选择是:
    ps-eo-pid,etime
    (返回pid的运行时间)。我将根据
    Process_Time = (current_time - boot_time) - (process_start_time)/HZ.
    
      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;
    
    ... stat kernel/system statistics

              cpu  3357 0 4313 1362393
                     The number of jiffies (1/100ths of a second)
                     that the system spent in user mode, user
                     mode with low priority (nice), system mode,
                     and the idle task, respectively.  The last
                     value should be 100 times the second entry
                     in the uptime pseudo-file.
    
              disk 0 0 0 0
                     The four disk entries are not implemented at
                     this time.  I'm not even sure what this
                     should be, since kernel statistics on other
                     machines usually track both transfer rate
                     and I/Os per second and this only allows for
                     one field per drive.
    
    //Original code credit by kmdent.
    //http://stackoverflow.com/questions/6514378/how-do-you-get-how-long-a-process-has-been-running
    #include <iostream>
    #include <iterator>
    #include <sstream>
    #include <fstream>
    #include <vector>
    #include <cstring>
    #include <cerrno>
    #include <ctime>
    #include <cstdio>
    #include <fcntl.h>
    #include <sys/time.h>
    
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string>
    #include "/usr/include/x86_64-linux-gnu/sys/param.h"
    
    using namespace std;
    
    
    template <class T>
    inline std::string to_string (const T& t)
    {
        std::stringstream ss;
        ss << t;
        return ss.str();
    }
    
    //Return the number of seconds a process has been running.
    long lapsed(string pid) {
    
        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;
        string f = "/proc/"+pid+"/stat";
        procFile.open(f.c_str());
    
        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));
    
        std::time_t now = std::time(0);
        std::time_t lapsed = ((now - boottime) - (atof(tmp.at(21).c_str()))/HZ);
        return lapsed;
    
    }
    
    string human_readable_lapsed(long input_seconds) {
        //Credit: http://www.cplusplus.com/forum/beginner/14357/
         long days = input_seconds / 60 / 60 / 24;
         int hours = (input_seconds / 60 / 60) % 24;
         int minutes = (input_seconds / 60) % 60;
         int seconds = input_seconds % 60;
    
         return "days: " + to_string(days) + " , hours: " + to_string(hours) + " , min: " + to_string(minutes) + " , seconds: " + to_string(seconds);
    }
    
    int main(int argc, char* argv[])
    {
        //Pid to get total running time for.
        string pid = "13875";
        std::cout << "Lapsed: " << human_readable_lapsed(lapsed(pid)) << std::endl;
        return 0;
    }