プロセスが消費できるメモリの量を制限するために、一部の JNI コードを変更しようとしています。Linux と osx で setRlimit をテストするために使用しているコードを次に示します。Linux では期待どおりに動作し、buf は null です。
このコードは、制限を 32 MB に設定してから、64 MB バッファーの割り当てを試みます。バッファーが null の場合、setrlimit は機能します。
#include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/resource.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
int main(int argc) {
pid_t pid = getpid();
struct rlimit current;
struct rlimit *newp;
int memLimit = 32 * 1024 * 1024;
int result = getrlimit(RLIMIT_AS, ¤t);
if (result != 0)
errExit("Unable to get rlimit");
current.rlim_cur = memLimit;
current.rlim_max = memLimit;
result = setrlimit(RLIMIT_AS, ¤t);
if (result != 0)
errExit("Unable to setrlimit");
printf("Doing malloc \n");
int memSize = 64 * 1024 * 1024;
char *buf = malloc(memSize);
if (buf == NULL) {
printf("Your out of memory\n");
} else {
printf("Malloc successsful\n");
}
free(buf);
}
Linuxマシンでは、これが私の結果です
memtest]$ ./m200k
Doing malloc
Your out of memory
OS X 10.8 の場合
./m200k
Doing malloc
Malloc successsful
私の質問は、これが osx で機能しない場合、darwin カーネルでこのタスクを実行する方法があるかということです。マニュアルページはすべて動作すると言っているようですが、動作しないようです。launchctl がメモリ制限をサポートしていることを見てきましたが、私の目標はこの機能をコードに追加することです。ulimit も使用してみましたが、これも機能せず、ulimit が setrlimit を使用して制限を設定していることは確かです。また、setrlimit のソフトまたはハードリミットを超えたときにキャッチできるシグナルはありますか。私はそれを見つけることができませんでした。
Windowsでも実行できる場合のボーナスポイント。
アドバイスをありがとう
更新
指摘したように、RLIMIT_AS はマニュアル ページで明示的に定義されていますが、RLIMIT_RSS として定義されているため、ドキュメントを参照すると、RLIMIT_RSS と RLIMIT_AS は OSX 上で交換可能です。
/usr/include/sys/resource.h osx 10.8 の場合
#define RLIMIT_RSS RLIMIT_AS /* source compatibility alias */
ここで説明されているRLIMIT_DATAを使用するというtrojanfoeの優れた提案をテストしました
The RLIMIT_DATA limit specifies the maximum amount of bytes the process
data segment can occupy. The data segment for a process is the area in which
dynamic memory is located (that is, memory allocated by malloc() in C, or in C++,
with new()). If this limit is exceeded, calls to allocate new memory will fail.
結果は linux と osx で同じで、どちらも malloc が成功しました。
chinshaw@osx$ ./m200k
Doing malloc
Malloc successsful
chinshaw@redhat ./m200k
Doing malloc
Malloc successsful