[英]Memory usage of child process in C
我閱讀了有關C語言中內存使用率計算的文章 ,並遇到了問題。
我編寫了簡單的測試程序,該程序可能工作一秒鍾以上,並使用1 KB以上的內存。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
int f[1000000];
sleep(1);
scanf("%d",&a);
printf("%d %d\n",a/10,a%10);
return 0;
}
然后我將其編譯為一些main.exe
並從文章中檢查程序操作
pid = fork();
if (pid == 0)
{
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = TIME_LIMIT;
setrlimit(RLIMIT_CPU, &rlim);
execv("./main.exe",NULL);
}
else
{
struct rusage resource_usage;
// set arbitrary lower limit value of memory used
int memory_used = 128;
pid_t pid2;
do {
memory_used = max(memory_used, get_memory_usage(pid));
if ((memory_used > memory_limit)
kill(pid, SIGKILL);
// wait for the child process to change state
pid2 = wait4(pid, &status, WUNTRACED | WCONTINUED, &resource_usage);
} while (pid2 == 0);
}
還有文章中的函數get_memory_usage()
int get_memory_usage(pid_t pid) {
int fd, data, stack;
char buf[4096], status_child[NAME_MAX];
char *vm;
sprintf(status_child, "/proc/%d/status", pid);
if ((fd = open(status_child, O_RDONLY)) < 0)
return -1;
read(fd, buf, 4095);
buf[4095] = '\0';
close(fd);
data = stack = 0;
vm = strstr(buf, "VmData:");
if (vm) {
sscanf(vm, "%*s %d", &data);
}
vm = strstr(buf, "VmStk:");
if (vm) {
sscanf(vm, "%*s %d", &stack);
}
return data + stack;
}
但是字符串中的問題,其中pid2 = wait4(pid, &status, WUNTRACED | WCONTINUED, &resource_usage);
。 while
僅進行一次迭代,然后等待過程結束。 但是我需要計算內存,而rusage resource_usage
不會給我這個信息。 在子進程運行並在其停止的地方停止時,我如何才能while
工作時獲得收益。 當他ZOMBIE時,子進程的狀態還有更多問題。 它不給記憶。 我也要抓 因為如果對於我的main.exe
我使用以下測試程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
int f[1000000];
sleep(1);
scanf("%d",&a);
printf("%d %d\n",a/10,a%10);
return 0;
}
當我在無限的while
從get_memory_usage
執行一些輸出while
,它顯示了所有/proc/[pid]/status
輸出。 而且我知道,那個子進程是
Name: check.exe
State: R (running)
在那之后
Name: main.exe
State: Z (zombie)
這意味着proc
無法在main.exe運行的地方捕獲信息。
根據waitpid()手冊頁所述,對wait4()
調用將一直阻塞,直到該進程停止為止,或者在停止后再次恢復。 這與阻塞等待輸入不同,這意味着它已被信號( SIGSTOP
)停止。
您需要的是WNOHANG
,它可以阻止wait4()
阻塞並使其立即返回,可能是這樣的:
do
{
// All the stuff you want to do
pid2 = wait4(pid, &status, WNOHANG, &resource_usage);
} while (pid2 == 0);
注意:我根本沒有測試以上內容,甚至沒有對其進行編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.