Last active
December 20, 2015 10:08
-
-
Save dojiong/6112755 to your computer and use it in GitHub Desktop.
获取程序运行的一些资源使用情况
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <sys/resource.h> | |
#include <sys/wait.h> | |
#include <signal.h> | |
int pid; | |
void sig_handler(int sig) { | |
if (pid > 0) { | |
kill(pid, sig); | |
} | |
} | |
int wait_exit() { | |
int status; | |
struct rusage ru; | |
if (wait4(pid, &status, 0, &ru) == -1) { | |
printf("wait child exit fail!\n"); | |
return -1; | |
} | |
printf("\n"); | |
printf("exit code: %d\n", status); | |
printf("sys time used: %d ms\n", | |
ru.ru_stime.tv_sec * 1000 + ru.ru_stime.tv_usec / 1000); | |
printf("usr time used: %d ms\n", | |
ru.ru_utime.tv_sec * 1000 + ru.ru_utime.tv_usec / 1000); | |
printf("maximum resident set size: %ld kb\n", ru.ru_maxrss); | |
printf("shared text segment memory: %d kb\n", ru.ru_ixrss); | |
printf("data segment memory: %d kb\n", ru.ru_idrss); | |
printf("stack memory: %d kb\n", ru.ru_isrss); | |
printf("soft page faults: %d kb\n", ru.ru_minflt); | |
printf("hard page faults: %d kb\n", ru.ru_majflt); | |
printf("file input operations: %d\n", ru.ru_inblock); | |
printf("file output operations: %d\n", ru.ru_oublock); | |
printf("voluntary context switches: %d\n", ru.ru_nvcsw); | |
return 0; | |
} | |
int run(char* const *cmd) { | |
pid = vfork(); | |
if (pid == -1) { | |
printf("vfork fail!\n"); | |
return -1; | |
} else if (pid == 0) { | |
execvp(cmd[0], cmd); | |
perror("execlp fail!"); | |
_exit(-1); | |
} else { | |
signal(SIGINT, sig_handler); | |
signal(SIGTERM, sig_handler); | |
signal(SIGHUP, sig_handler); | |
return wait_exit(pid); | |
} | |
} | |
int main(int argc, char const *argv[]) { | |
pid = 0; | |
if (argc < 2) { | |
printf("usage: %s cmd\n", argv[0]); | |
return -1; | |
} | |
return run((char* const*)(argv+1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment