Legend:
Library
Module
Module type
Parameter
Class
Class type
Low-level interface to the operating system (both Unix and Windows).
This module only provides low-level functions and types. Unless you know that you need low-level access to the operating system, you probably don't. For higher-level functions, see modules BatIO, BatFile.
Raised by the system calls below when an error is encountered. The first component is the error code; the second component is the function name; the third component is the string parameter to the function, if it has one, or the empty string otherwise.
handle_unix_error f x applies f to x and returns the result. If the exception Unix_error is raised, it prints a message describing the error and exits with code 2.
Access to the process environment
val environment : unit ->string array
Return the process environment, as an array of strings with the format ``variable=value''.
val getenv : string -> string
Return the value associated to a variable in the process environment.
raisesNot_found
if the variable is unbound. (This function is identical to Sys.getenv.)
val putenv : string ->string -> unit
Unix.putenv name value sets the value associated to a variable in the process environment. name is the name of the environment variable, and value its new associated value.
The process terminated normally by exit; the argument is the return code.
*)
| WSIGNALEDof int
(*
The process was killed by a signal; the argument is the signal number.
*)
| WSTOPPEDof int
(*
The process was stopped by a signal; the argument is the signal number.
*)
The termination status of a process. See module Sys for the definitions of the standard signal numbers. Note that they are not the numbers used by the OS.
execv prog args execute the program in file prog, with the arguments args, and the current process environment. These execv* functions never return: on success, the current program is replaced by the new one;
Same as Unix.wait, but waits for the child process whose pid is given. A pid of -1 means wait for any child. A pid of 0 means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whether waitpid should return immediately without waiting, or also report stopped children.
Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell /bin/sh and therefore can contain redirections, quotes, variables, etc. The result WEXITED 127 indicates that the shell couldn't be executed.
(stat, output) = run_and_read cmd run the command cmd (via Unix.system) then return its exit status stat and output string output as read from its standard output (which was redirected to a temporary file).
since 2.4
val getpid : unit -> int
Return the pid of the process.
val getppid : unit -> int
Return the pid of the parent process.
val nice : int -> int
Change the process priority. The integer argument is added to the ``nice'' value. (Higher values of the ``nice'' value mean lower priorities.) Return the new nice value.
Open the named file with the given flags. Third argument is the permissions to give to the file if it is created. Return a file descriptor on the named file.
read fd buff ofs len reads len characters from descriptor fd, storing them in string buff, starting at position ofs in string buff. Return the number of characters actually read.
write fd buff ofs len writes len characters to descriptor fd, taking them from string buff, starting at position ofs in string buff. Return the number of characters actually written. write repeats the writing operation until all characters have been written or an error occurs.
Create an input reading from the given descriptor. The input is initially in binary mode; use set_binary_mode_in ic false if text mode is desired.
parameterautoclose
If true (default value), close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
parametercleanup
If true, close the underlying file descriptor when the input is closed. If false or unspecified, do nothing, in which case you will need to close the underlying file descriptor yourself to ensure proper cleanup.
Create an output writing on the given descriptor. The output is initially in binary mode; use set_binary_mode_out oc false if text mode is desired.
parametercleanup
If true, close the underlying file descriptor when the output is closed. If false or unspecified, do nothing, in which case you will need to close the underlying file descriptor yourself to ensure proper cleanup.
File operations on large files. This sub-module provides 64-bit variants of the functions Unix.lseek (for positioning a file descriptor), Unix.truncate and Unix.ftruncate (for changing the size of a file), and Unix.stat, Unix.lstat and Unix.fstat (for obtaining information on files). These alternate functions represent positions and sizes by 64-bit integers (type int64) instead of regular integers (type int), thus allowing operating on files whose sizes are greater than max_int.
Operations on file names
val unlink : string -> unit
Removes the named file
val rename : string ->string -> unit
rename old new changes the name of a file from old to new.
val link : string ->string -> unit
link source dest creates a hard link named dest to the file named source.
Set the ``non-blocking'' flag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises EAGAIN or EWOULDBLOCK error instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raises EAGAIN or EWOULDBLOCK.
Set the ``close-on-exec'' flag on the given descriptor. A descriptor with the close-on-exec flag is automatically closed when the current process starts another program with one of the exec functions.
Create a pipe. The first component of the result is opened for reading, that's the exit to the pipe. The second component is opened for writing, that's the entrance to the pipe.
val open_process_in :
?autoclose:bool ->?cleanup:bool ->string ->BatInnerIO.input
High-level pipe and process management. This function runs the given command in parallel with the program. The standard output of the command is redirected to a pipe, which can be read via the returned input. The command is interpreted by the shell /bin/sh (cf. system).
parameterautoclose
If true (default value), close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
parametercleanup
If true or unspecified, close the process when the input is closed. If false, do nothing, in which case you will need to close the process yourself to ensure proper cleanup.
val open_process_out : ?cleanup:bool ->string ->unit BatInnerIO.output
Same as Unix.open_process_in, but redirect the standard input of the command to a pipe. Data written to the returned output is sent to the standard input of the command.
Warning writes on outputs are buffered, hence be careful to call Pervasives.flush at the right times to ensure correct synchronization.
parametercleanup
If true or unspecified, close the process when the output is closed. If false, do nothing, in which case you will need to close the process yourself to ensure proper cleanup.
Same as Unix.open_process_out, but redirects both the standard input and standard output of the command to pipes connected to the two returned input/output. The returned input is connected to the output of the command, and the returned output to the input of the command.
parameterautoclose
If true (default value), close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
parametercleanup
If true or unspecified, close the process when either the output or the output is closed. If false, do nothing, in which case you will need to close the process yourself to ensure proper cleanup.
Similar to Unix.open_process, but the second argument specifies the environment passed to the command. The result is a triple of input/output connected respectively to the standard output, standard input, and standard error of the command.
parameterautoclose
If true (default value), close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
parametercleanup
If true or unspecified, close the process when either the output or the output is closed. If false, do nothing, in which case you will need to close the process yourself to ensure proper cleanup.
create_process prog args new_stdin new_stdout new_stderr forks a new process that executes the program in file prog, with arguments args. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The standard input and outputs of the new process are connected to the descriptors new_stdin, new_stdout and new_stderr. Passing e.g. stdout for new_stdout prevents the redirection and causes the new process to have the same standard output as the current process. The executable file prog is searched in the path. The new process has the same environment as the current process.
create_process_env prog args env new_stdin new_stdout new_stderr works as Unix.create_process, except that the extra argument env specifies the environment passed to the program.
val symlink : ?to_dir:bool ->string ->string -> unit
Symbolic links
symlink ?to_dir source dest creates the file dest as a symbolic link to the file source. On Windows, ~to_dir indicates if the symbolic link points to a directory or a file; if omitted, symlink examines source using stat and picks appropriately, if source does not exist then false is assumed (for this reason, it is recommended that the ~to_dir parameter be specified in new code). On Unix, ~to_dir ignored.
Windows symbolic links are available in Windows Vista onwards. There are some important differences between Windows symlinks and their POSIX counterparts.
Windows symbolic links come in two flavours: directory and regular, which designate whether the symbolic link points to a directory or a file. The type must be correct - a directory symlink which actually points to a file cannot be selected with chdir and a file symlink which actually points to a directory cannot be read or written (note that Cygwin's emulation layer ignores this distinction).
When symbolic links are created to existing targets, this distinction doesn't matter and symlink will automatically create the correct kind of symbolic link. The distinction matters when a symbolic link is created to a non-existent target.
The other caveat is that by default symbolic links are a privileged operation. Administrators will always need to be running elevated (or with UAC disabled) and by default normal user accounts need to be granted the SeCreateSymbolicLinkPrivilege via Local Security Policy (secpol.msc) or via Active Directory.
has_symlink can be used to check that a process is able to create symbolic links.
since 4.03 the optional argument ?to_dir was added in 4.03
val has_symlink : unit -> bool
Returns true if the user is able to create symbolic links. On Windows, this indicates that the user not only has the SeCreateSymbolicLinkPrivilege but is also running elevated, if necessary. On other platforms, this is simply indicates that the symlink system call is available.
Wait until some input/output operations become possible on some channels. The three list arguments are, respectively, a set of descriptors to check for reading (first argument), for writing (second argument), or for exceptional conditions (third argument). The fourth argument is the maximal timeout, in seconds; a negative fourth argument means no timeout (unbounded wait). The result is composed of three sets of descriptors: those ready for reading (first component), ready for writing (second component), and over which an exceptional condition is pending (third component).
lockf fd cmd size puts a lock on a region of the file opened as fd. The region starts at the current read/write position for fd (as set by Unix.lseek), and extends size bytes forward if size is positive, size bytes backwards if size is negative, or to the end of the file if size is zero. A write lock prevents any other process from acquiring a read or write lock on the region. A read lock prevents any other process from acquiring a write lock on the region, but lets other processes acquire read locks on it.
The F_LOCK and F_TLOCK commands attempts to put a write lock on the specified region. The F_RLOCK and F_TRLOCK commands attempts to put a read lock on the specified region. If one or several locks put by another process prevent the current process from acquiring the lock, F_LOCK and F_RLOCK block until these locks are removed, while F_TLOCK and F_TRLOCK fail immediately with an exception. The F_ULOCK removes whatever locks the current process has on the specified region. Finally, the F_TEST command tests whether a write lock can be acquired on the specified region, without actually putting a lock. It returns immediately if successful, or fails otherwise.
val with_locked_file :
kind:[ `Read | `Write ]->string ->(file_descr->'a)->'a
with_locked_file ~kind filename f puts a lock (using lockf) on the whole file named filename, calls f with the file descriptor, and returns its result after the file is unlocked. The file is opened with permissions matching kind, and created if it does not exist yet. If f () raises an exception the exception is re-raised after the file is unlocked.
parameterkind
specifies whether the lock is read-only or read-write.
Signals
Note: installation of signal handlers is performed via the functions Sys.signal and Sys.set_signal.
val kill : int ->int -> unit
kill pid sig sends signal number sig to the process with id pid.
sigprocmask cmd sigs changes the set of blocked signals. If cmd is SIG_SETMASK, blocked signals are set to those in the list sigs. If cmd is SIG_BLOCK, the signals in sigs are added to the set of blocked signals. If cmd is SIG_UNBLOCK, the signals in sigs are removed from the set of blocked signals. sigprocmask returns the set of previously blocked signals.
val sigpending : unit ->int list
Return the set of blocked signals that are currently pending.
val sigsuspend : int list-> unit
sigsuspend sigs atomically sets the blocked signals to sigs and waits for a non-ignored, non-blocked signal to be delivered. On return, the blocked signals are reset to their initial value.
val pause : unit -> unit
Wait until a non-ignored, non-blocked signal is delivered.
Convert a date and time, specified by the tm argument, into a time in seconds, as returned by Unix.time. The tm_isdst, tm_wday and tm_yday fields of tm are ignored. Also return a normalized copy of the given tm record, with the tm_wday, tm_yday, and tm_isdst fields recomputed from the other fields, and the other fields normalized (so that, e.g., 40 October is changed into 9 November). The tm argument is interpreted in the local time zone.
val alarm : int -> int
Schedule a SIGALRM signal after the given number of seconds.
val sleep : int -> unit
Stop execution for the given number of seconds.
val sleepf : float -> unit
Stop execution for the given number of seconds. Like sleep, but fractions of seconds are supported.
Set the last access time (second arg) and last modification time (third arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970. A time of 0.0 is interpreted as the current time.
setitimer t s sets the interval timer t and returns its previous status. The s argument is interpreted as follows: s.it_value, if nonzero, is the time to the next timer expiration; s.it_interval, if nonzero, specifies a value to be used in reloading it_value when the timer expires. Setting s.it_value to zero disable the timer. Setting s.it_interval to zero causes the timer to be disabled after its next expiration.
User id, group id
val getuid : unit -> int
Return the user id of the user executing the process.
val geteuid : unit -> int
Return the effective user id under which the process runs.
val setuid : int -> unit
Set the real user id and effective user id for the process.
val getgid : unit -> int
Return the group id of the user executing the process.
val getegid : unit -> int
Return the effective group id under which the process runs.
val setgid : int -> unit
Set the real group id and effective group id for the process.
val getgroups : unit ->int array
Return the list of groups to which the user executing the process belongs.
val setgroups : int array-> unit
setgroups groups sets the supplementary group IDs for the calling process. Appropriate privileges are required.
val initgroups : string ->int -> unit
initgroups user group initializes the group access list by reading the group database /etc/group and using all groups of which user is a member. The additional group group is also added to the list.
Conversion from the printable representation of an Internet address to its internal representation. The argument string consists of 4 numbers separated by periods (XXX.YYY.ZZZ.TTT) for IPv4 addresses, and up to 8 numbers separated by colons for IPv6 addresses.
raisesFailure
when given a string that does not match these formats.
The type of socket addresses. ADDR_UNIX name is a socket address in the Unix domain; name is a file name in the file system. ADDR_INET(addr,port) is a socket address in the Internet domain; addr is the Internet address of the machine, and port is the port number.
Create a new socket in the given domain, and with the given kind. The third argument is the protocol type; 0 selects the default protocol for that kind of sockets.
Accept connections on the given socket. The returned descriptor is a socket connected to the client; the returned address is the address of the connecting client.
Shutdown a socket connection. SHUTDOWN_SEND as second argument causes reads on the other end of the connection to return an end-of-file condition. SHUTDOWN_RECEIVE causes writes on the other end of the connection to return a closed pipe condition (SIGPIPE signal).
Whether to linger on closed connections that have data present, and for how long (in seconds)
*)
The socket options that can be consulted with Unix.getsockopt_optint and modified with Unix.setsockopt_optint. These options have a value of type int option, with None meaning ``disabled''.
The socket options that can be consulted with Unix.getsockopt_float and modified with Unix.setsockopt_float. These options have a floating-point value representing a time in seconds. The value 0 means infinite timeout.
Connect to a server at the given address. Return a pair of input/output connected to the server. The connection is closed whenever either the input or the output is closed.
Remember to call Pervasives.flush on the output at the right times to ensure correct synchronization.
parameterautoclose
If true (default value), close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
``Shut down'' a connection established with Unix.open_connection; that is, transmit an end-of-file condition to the server reading on the other side of the connection.
deprecated
Connections do not require a special function anymore. Use regular function BatIO.close_in for closing connections.
establish_server f addr establishes a server on address addr. For each connection on this address, function f is called with two buffered channels connected to the client. A new process is created for each connection. The function Unix.establish_server never returns normally.
parameterautoclose
If true (default value), inputs passed to f close the input automatically once there is no more content to read. Otherwise, the input will be closed according to the usual rules of module BatIO. Barring very specific needs (e.g. using file descriptors as locks), you probably want autoclose to be true.
parametercleanup
If true or unspecified, close the connection when the input or the output is closed or garbage-collected. If false, do nothing, in which case you will need to shutdown the connection using shutdown_connection to ensure proper cleanup.
getaddrinfo host service opts returns a list of Unix.addr_info records describing socket parameters and addresses suitable for communicating with the given host and service. The empty list is returned if the host or service names are unknown, or the constraints expressed in opts cannot be satisfied.
host is either a host name or the string representation of an IP address. host can be given as the empty string; in this case, the ``any'' address or the ``loopback'' address are used, depending whether opts contains AI_PASSIVE. service is either a service name or the string representation of a port number. service can be given as the empty string; in this case, the port field of the returned addresses is set to 0. opts is a possibly empty list of options that allows the caller to force a particular socket domain (e.g. IPv6 only or IPv4 only) or a particular socket type (e.g. TCP only or UDP only).
getnameinfo addr opts returns the host name and service name corresponding to the socket address addr. opts is a possibly empty list of options that governs how these names are obtained.
raisesNot_found
if an error occurs.
Terminal interface
The following functions implement the POSIX standard terminal interface. They provide control over asynchronous communication ports and pseudo-terminals. Refer to the termios man page for a complete description.
Set the status of the terminal referred to by the given file descriptor. The second argument indicates when the status change takes place: immediately (TCSANOW), when all pending output has been transmitted (TCSADRAIN), or after flushing all input that has been received but not read (TCSAFLUSH). TCSADRAIN is recommended when changing the output parameters; TCSAFLUSH, when changing the input parameters.
Send a break condition on the given file descriptor. The second argument is the duration of the break, in 0.1s units; 0 means standard duration (0.25s).
Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: TCIFLUSH flushes data received but not read, TCOFLUSH flushes data written but not transmitted, and TCIOFLUSH flushes both.
Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: TCOOFF suspends output, TCOON restarts output, TCIOFF transmits a STOP character to suspend input, and TCION transmits a START character to restart input.
val setsid : unit -> int
Put the calling process in a new session and detach it from its controlling terminal.
Small tools
val is_directory : string -> bool
is_directory filename returns true if filename refers to a directory (or symlink of a directory)
val restart_on_EINTR : ('a->'b)->'a->'b
restart_on_EINTR f x invokes f on x repetedly until the function returns a value or raises another exception than EINTR.
Thread-safety internals
Unless you are attempting to adapt Batteries Included to a new model of concurrency, you probably won't need this.
By default, this is BatConcurrent.nolock. However, if you're using a version of Batteries compiled in threaded mode, this uses BatMutex. If you're attempting to use Batteries with another concurrency model, set the lock appropriately.