有没有办法从/proc目录中获取此信息?我希望能够获得每个进程在几秒钟内运行了多长时间。
编辑:我需要在C++中执行此操作。很抱歉给你造成了混乱。
发布于 2011-07-02 05:37:42
好了,在阅读了top命令的源代码之后,我想出了一种获取进程开始时间的简单方法。他们使用的公式是:
Process_Time = (current_time - boot_time) - (process_start_time)/HZ.(你必须除以HZ,因为process_start_time在jiffies中)
获取以下值:
current_time -您可以从C命令gettimeofday().boot_time中获取该值-该值位于/proc/uptime中。该文件包含两个数字:系统的正常运行时间(秒)和空闲进程中花费的时间量(秒)。获取first.process_start_time -该值位于/proc/[PID]/stat中。系统启动和进程启动之间的时间差( jiffies)。(如果在whitespace).上拆分,则为文件中的第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;祝你编码愉快!
发布于 2011-06-29 08:03:11
您可以执行stat /proc/{processid}来查看shell的创建时间。
编辑:该文件夹上的fstat应该会提供您想要的内容(创建时间)。
发布于 2011-06-29 08:26:47
让我们来分析一下你要做的事情:
因此,为了获得当前时间,我们可以运行:
#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.现在,下一步是将其解析为Unix时间--但我们不必这样做!X说明符实际上将其转换为Unix时间。因此,下一步将是(a)获得当前时间(b)减去时间:
timeval cur_time;
double current_time, time_passed;
char read_time[11]; // 32 bit overflows = only 11 digits.
FILE *ourpipe;
gettimeofday(&cur_time, NULL);
current_time = cur_time.tv_sec + (cur_time.tv_usec * 1000000.0);
// usec stands for mu second, i.e., a millionth of a second. I wasn't there when they named this stuff.
ourpipe = fopen ("time_pipe", "rb");
fread(read_time, sizeof (char), 10, ourpipe);
time_passed = current_time - atoi (read_time);
fclose (ourpipe);所以,是的,差不多就是这样。需要管道将输入从一个管道传递到另一个管道。
https://stackoverflow.com/questions/6514378
复制相似问题