简体   繁体   English

如何限制子进程中的内存使用,并在Linux上出现内存不足时进行检查

[英]How to limit the memory usage in subprocess and check it when out of memory on Linux

I use the setrlimit API to limit the sub-process resources and check it on the parent process. 我使用setrlimit API限制子流程资源,并在父流程中进行检查。

When the sub-process exceed the memory limit, it will be terminated by a SIGSEV signal, but I have some other reasons also cause the SIGSEV signal, so I can't judge whether the sub-process exceeded the memory limit. 当子进程超出内存限制时,它将被SIGSEV信号终止,但是我还有其他原因也会导致SIGSEV信号,因此我无法判断子进程是否超出了内存限制。

Is there a way to know whether the sub-process exceed the memory limit? 有没有办法知道子进程是否超出了内存限制?

This depends on which limit was hit. 这取决于达到哪个限制。

If your memory limits ( -d , -v ) are hit, malloc (resp. the underlying brk()/sbrk() -call) will fail with NULL as return value. 如果达到您的内存限制( -d-v ),则malloc(分别是底层的brk()/sbrk() call)将失败,返回值为NULL Your program will only segfault now, if this error condition isn't checked. 如果未选中此错误条件,则您的程序现在只会进行segfault。 You could check for an access near address 0 (struct member access) and then try to guess, if it is an unchecked malloc access. 您可以检查地址0 附近的访问(结构成员访问),然后尝试猜测是否是未经检查的malloc访问。 If you know, that you do not do malloc checks anywhere, you could also write a wrapper with an assert(ret != NULL); 如果您知道自己不在任何地方进行malloc检查,则还可以编写一个带有assert(ret != NULL);的包装器assert(ret != NULL); or similar. 或类似。

If the stack limit ( -s ) is reached, the situation is different; 如果达到了堆栈限制( -s ),则情况有所不同; A process simply accesses memory in the vincity of the stack and the operation system automatically enlarges the stack; 一个进程只需要访问堆栈中的内存即可,操作系统会自动扩大堆栈。 or it doesn't, if the limit is hit. 如果没有达到限制,则不会。 You can identify this by looking at the address, which caused the fault (in the siginfo_t structure of your handler), and checking, if it is near your stack. 您可以通过查看引起故障的地址(在处理程序的siginfo_t结构中)并检查其是否在堆栈附近来识别此错误。

All other ulimits shouldn't generate segfaults. 所有其他ulimit均不应生成段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM