There are two ways this can be done:
- using the
ulimit shell utility, or using the
setrlimit system call (which is what
ulimit calls in turn).
- using filesystem quotas, and a special user for the server process, will restrict the total usage of that user
man 2 setrlimit:
The maximum size of files that the process may create. Attempts
to extend a file beyond this limit result in delivery of a
SIGXFSZ signal. By default, this signal terminates a process,
but a process can catch this signal instead, in which case the
relevant system call (e.g., write(2), truncate(2)) fails with
the error EFBIG.
I'm not sure how one could invoke the
setrlimit function from Java, but this U&L question might help. Alternatively, wrap the Java server in a script:
ulimit -f 1073741824 # 1GB
I'm assuming an ext4 filesystem, I'm unsure about others. First, we need to enable quota on the filesystem. Edit
/etc/fstab, and add
usrquota to the mount options of the appropriate partition. If we're doing this for
/, for example, the final entry would look something like:
UUID=... / ext4 errors=remount-ro,usrquota 0 1
Then enable it after restarting:
sudo quotaon /
I'll assume your server is run as a different user (say
restricted_user). If not, create one if you don't want your normal processes to be affected.
sudo edquota restricted_user
Which will open an editor.
Disk quotas for user restricted_user (uid 1001):
Filesystem blocks soft hard inodes soft hard
/dev/sdd1 1087940 943718 1048576 9956 0 0
Set the soft and hard limits to the appropriate values (they're 1024-byte blocks, so divide your limit by 1024). Save and quit.
Then the user will not be able to exceed a total of 1G usage on that filesystem, counting all files owned by them.
Naturally, you should still check the size in your server program.