linux使用select()定时器统计进程运行时间
时间: 2023-04-26 21:05:18 浏览: 152
使用select()函数可以实现定时器功能,可以用来统计进程运行时间。
具体实现方法如下:
1. 定义一个结构体,用来存储进程的运行时间和文件描述符。
2. 使用select()函数来监听文件描述符,设置超时时间为1秒。
3. 如果有文件描述符就绪,说明进程在运行,更新进程的运行时间。
4. 如果超时,说明进程已经结束,输出进程的运行时间。
代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
struct process {
int fd;
double runtime;
};
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <command>\n", argv[]);
exit(1);
}
int fd[2];
if (pipe(fd) < ) {
perror("pipe");
exit(1);
}
pid_t pid = fork();
if (pid < ) {
perror("fork");
exit(1);
} else if (pid == ) {
close(fd[]);
dup2(fd[1], STDOUT_FILENO);
execvp(argv[1], &argv[1]);
perror("execvp");
exit(1);
} else {
close(fd[1]);
struct process p = {fd[], };
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(p.fd, &rfds);
struct timeval tv = {1, };
while (select(p.fd + 1, &rfds, NULL, NULL, &tv) > ) {
if (FD_ISSET(p.fd, &rfds)) {
char buf[1024];
int n = read(p.fd, buf, sizeof(buf));
if (n < ) {
perror("read");
exit(1);
} else if (n == ) {
break;
} else {
p.runtime += tv.tv_sec + tv.tv_usec / 100000.;
}
}
FD_ZERO(&rfds);
FD_SET(p.fd, &rfds);
tv.tv_sec = 1;
tv.tv_usec = ;
}
printf("Process %d runtime: %.2f seconds\n", pid, p.runtime);
}
return ;
}
```