c - C中子进程的内存使用

标签 c linux memory fork

我读了article关于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 只进行一次迭代并等待流程结束。但是我需要计算内存,usage 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 执行一些输出时,它会显示所有 /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);

注意我根本没有测试上面的内容,甚至没有编译它。

关于c - C中子进程的内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655994/

相关文章:

c - 定义 union 时在 eclipse CDT 中出现语法错误 "type XXX could not be resolved"

linux - 如何使用sed从字符串中的特定点提取文本?

c - 在 main.c 中定义其他头文件所需的宏的传统方法是什么?

我可以将父进程的 stderr 重定向到 fork 进程上的套接字文件描述符吗?

linux - QT版本未正确安装,请运行make install

memory - 如何记录 malloc

Java transient 运行时改进?

C - 返回指针的函数,如何编写高效的代码?

python ctypes加载dll返回新的malloc'd缓冲区

linux - 如何在连续的行中为我的 vi 编辑器添加前缀?