如何限制生成的程序可以在C ++中使用的内存量 [英] How to limit the amount of memory a spawned program can use in C++

查看:114
本文介绍了如何限制生成的程序可以在C ++中使用的内存量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的c ++程序中,我将开始其他程序。如果这些程序使用超过一定量的内存,我希望我的程序杀死他们的进程。如何做到这一点?

In my c++ program I am going to start other programs. If those programs use over a certain amount of memory, I want my program to kill their processes. How can that be done?

我可能会使用execv来启动程序。

I will probably use execv to start the programs.

推荐答案

假设你在一个POSIX系统上,你可以通过调用 fork()之后调用 setrlimit(2) 。例如:

Assuming, you're on a POSIX system, you can limit this by calling setrlimit(2) after fork(). For example:

if (fork() == 0) {
    struct rlimit limits;
    limits.rlim_cur = 10000000; // set data segment limit to 10MB
    limits.rlim_max = 10000000; // make sure the child can't increase it again
    setrlimit(RLIMIT_DATA, &limits);
    execv(...);
}

如果您的子进程尝试分配更多的内存,自动杀死,但它将无法满足内存分配请求。如果子程序在这种情况下选择中止,那么它将死亡。如果它选择继续,父母将不会被通知这种情况。

If your child process attempts to allocate more memory than this, it won't be killed automatically, but it will fail to satisfy memory allocation requests. If the child program chooses to abort in this situation, then it will die. If it chooses to continue, the parent won't be notified of this situation.

这篇关于如何限制生成的程序可以在C ++中使用的内存量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆