SWI-Prolog C-library
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • SWI-Prolog C-library
        • Introduction
        • library(process): Create processes and redirect I/O
        • library(filesex): Extended operations on files
        • library(uid): User and group management on Unix systems
        • library(syslog): Unix syslog interface
        • library(socket): Network socket (TCP and UDP) library
        • The stream_pool library
        • library(uri): Process URIs
        • CGI Support library
        • Password encryption library
        • library(uuid): Universally Unique Identifier (UUID) Library
        • SHA* Secure Hash Algorithms
        • library(md5): MD5 hashes
        • library(hash_stream): Maintain a hash on a stream
        • Memory files
        • Time and alarm library
        • library(unix): Unix specific operations
        • Limiting process resources
          • rlimit/3
        • library(udp_broadcast): A UDP broadcast proxy
        • library(prolog_stream): A stream with Prolog callbacks

18 Limiting process resources

The library(rlimit) library provides an interface to the POSIX getrlimit()/setrlimit() API that control the maximum resource-usage of a process or group of processes. This call is especially useful for servers such as CGI scripts and inetd-controlled servers to avoid an uncontrolled script claiming too much resources.

rlimit(+Resource, -Old, +New)
Query and/or set the limit for Resource. Time-values are in seconds and size-values are counted in bytes. The following values are supported by this library. Please note that not all resources may be available and accessible on all platforms. This predicate can throw a variety of exceptions. In portable code this should be guarded with catch/3. The defined resources are:
as Max address space
cpu CPU time in seconds
fsize Maximum filesize
data max data size
stack max stack size
core max core file size
rss max resident set size
nproc max number of processes
nofile max number of open files
memlock max locked-in-memory address

When the process hits a limit POSIX systems normally send the process a signal that terminates it. These signals may be caught using SWI-Prolog's on_signal/3 primitive. The code below illustrates this behaviour. Please note that asynchronous signal handling is dangerous, especially when using threads. 100% fail-safe operation cannot be guaranteed, but this procedure will inform the user properly‘most of the time'.

rlimit_demo :-
        rlimit(cpu, _, 2),
        on_signal(xcpu, _, cpu_exceeded),
        ( repeat, fail ).

cpu_exceeded(_Sig) :-
        format(user_error, 'CPU time exceeded~n', []),
        halt(1).