Puede limitar el tamaño de la memoria virtual de su proceso utilizando los límites del sistema. Si procesa excede esta cantidad, se matará con una señal (creo que SIGBUS).
Usted puede usar algo como:
#include <sys/resource.h>
#include <iostream>
using namespace std;
class RLimit {
public:
RLimit(int cmd) : mCmd(cmd) {
}
void set(rlim_t value) {
clog << "Setting " << mCmd << " to " << value << endl;
struct rlimit rlim;
rlim.rlim_cur = value;
rlim.rlim_max = value;
int ret = setrlimit(mCmd, &rlim);
if (ret) {
clog << "Error setting rlimit" << endl;
}
}
rlim_t getCurrent() {
struct rlimit rlim = {0, 0};
if (getrlimit(mCmd, &rlim)) {
clog << "Error in getrlimit" << endl;
return 0;
}
return rlim.rlim_cur;
}
rlim_t getMax() {
struct rlimit rlim = {0, 0};
if (getrlimit(mCmd, &rlim)) {
clog << "Error in getrlimit" << endl;
return 0;
}
return rlim.rlim_max;
}
private:
int mCmd;
};
y luego usarlo como esa:
RLimit dataLimit(RLIMIT_DATA);
dataLimit.set(128 * 1024); // in kB
clog << "soft: " << dataLimit.getCurrent() << " hard: " << dataLimit.getMax() << endl;
Esta aplicación parece un poco prolijo pero le permite configurar fácilmente y limpiamente diferentes límites (ver ulimit -a
)
¿Por qué no solo verifica el tamaño del archivo? –