ocaml-base-compiler
- Error report
- Access to the process environment
- Process handling
- Basic file input/output
- Interfacing with the standard input/output library
- Seeking and truncating
- File status
- File operations on large files
- Mapping files into memory
- Operations on file names
- File permissions and ownership
- Operations on file descriptors
- Directories
- Pipes and redirections
- High-level process and redirection management
- Symbolic links
- Polling
- Locking
- Signals
- Time functions
- User id, group id
- Internet addresses
- Sockets
- Socket options
- High-level network connection functions
- Host and protocol databases
- Terminal interface
Library
Module
Module type
Parameter
Class
Class type
Error report
type error =
The type of error codes. Errors defined in the POSIX standard and additional errors from UNIX98 and BSD. All other errors are mapped to EUNKNOWNERR.
exception Unix_error of error * string * string
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.
UnixLabels.Unix_error
and Unix.Unix_error
are the same, and catching one will catch the other.
val error_message : error -> string
Return a string describing the given error code.
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
Return the process environment, as an array of strings with the format ``variable=value''. The returned array is empty if the process has special privileges.
Return the process environment, as an array of strings with the format ``variable=value''. Unlike environment
, this function returns a populated array even if the process has special privileges. See the documentation for unsafe_getenv
for more details.
Return the value associated to a variable in the process environment, unless the process has special privileges.
Return the value associated to a variable in the process environment.
Unlike getenv
, this function returns the value even if the process has special privileges. It is considered unsafe because the programmer of a setuid or setgid program must be careful to avoid using maliciously crafted environment variables in the search path for executables, the locations for temporary files or logs, and the like.
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.
Process handling
type process_status =
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.
type wait_flag =
| WNOHANG | (* Do not block if no child has died yet, but immediately return with a pid equal to 0. *) |
| WUNTRACED | (* Report also the children that receive stop signals. *) |
Flags for waitpid
.
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 execv
, except that the third argument provides the environment to the program executed.
Same as execv
, except that the program is searched in the path.
Same as execve
, except that the program is searched in the path.
Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process.
val wait : unit -> int * process_status
Wait until one of the children processes die, and return its pid and termination status.
val waitpid : wait_flag list -> int -> int * process_status
Same as 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, and whether it should report stopped children.
On Windows: can only wait for a given PID, not any child process.
val system : string -> process_status
Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell /bin/sh
(or the command interpreter cmd.exe
on Windows) and therefore can contain redirections, quotes, variables, etc. To properly quote whitespace and shell special characters occurring in file names or command arguments, the use of Filename.quote_command
is recommended. The result WEXITED 127
indicates that the shell couldn't be executed.
Terminate the calling process immediately, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. Unlike Stdlib.exit
, Unix._exit
performs no finalization whatsoever: functions registered with Stdlib.at_exit
are not called, input/output channels are not flushed, and the C run-time system is not finalized either.
The typical use of Unix._exit
is after a Unix.fork
operation, when the child process runs into a fatal error and must exit. In this case, it is preferable to not perform any finalization action in the child process, as these actions could interfere with similar actions performed by the parent process. For example, output channels should not be flushed by the child process, as the parent process may flush them again later, resulting in duplicate output.
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.
Basic file input/output
val stdin : file_descr
File descriptor for standard input.
val stdout : file_descr
File descriptor for standard output.
val stderr : file_descr
File descriptor for standard error.
type open_flag =
| O_RDONLY | (* Open for reading *) |
| O_WRONLY | (* Open for writing *) |
| O_RDWR | (* Open for reading and writing *) |
| O_NONBLOCK | (* Open in non-blocking mode *) |
| O_APPEND | (* Open for append *) |
| O_CREAT | (* Create if nonexistent *) |
| O_TRUNC | (* Truncate to 0 length if existing *) |
| O_EXCL | (* Fail if existing *) |
| O_NOCTTY | (* Don't make this dev a controlling tty *) |
| O_DSYNC | (* Writes complete as `Synchronised I/O data integrity completion' *) |
| O_SYNC | (* Writes complete as `Synchronised I/O file integrity completion' *) |
| O_RSYNC | (* Reads complete as writes (depending on O_SYNC/O_DSYNC) *) |
| O_SHARE_DELETE | (* Windows only: allow the file to be deleted while still open *) |
| O_CLOEXEC | (* Set the close-on-exec flag on the descriptor returned by |
| O_KEEPEXEC | (* Clear the close-on-exec flag. This is currently the default. *) |
The flags to openfile
.
The type of file access rights, e.g. 0o640
is read and write for user, read for group, none for others
val openfile : string -> open_flag list -> file_perm -> file_descr
Open the named file with the given flags. Third argument is the permissions to give to the file if it is created (see umask
). Return a file descriptor on the named file.
val close : file_descr -> unit
Close a file descriptor.
val fsync : file_descr -> unit
Flush file buffers to disk.
val read : file_descr -> bytes -> int -> int -> int
read fd buf pos len
reads len
bytes from descriptor fd
, storing them in byte sequence buf
, starting at position pos
in buf
. Return the number of bytes actually read.
val write : file_descr -> bytes -> int -> int -> int
write fd buf pos len
writes len
bytes to descriptor fd
, taking them from byte sequence buf
, starting at position pos
in buff
. Return the number of bytes actually written. write
repeats the writing operation until all bytes have been written or an error occurs.
val single_write : file_descr -> bytes -> int -> int -> int
Same as write
, but attempts to write only once. Thus, if an error occurs, single_write
guarantees that no data has been written.
val write_substring : file_descr -> string -> int -> int -> int
Same as write
, but take the data from a string instead of a byte sequence.
val single_write_substring : file_descr -> string -> int -> int -> int
Same as single_write
, but take the data from a string instead of a byte sequence.
Interfacing with the standard input/output library
val in_channel_of_descr : file_descr -> in_channel
Create an input channel reading from the given descriptor. The channel is initially in binary mode; use set_binary_mode_in ic false
if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: Stdlib.set_binary_mode_in
always fails on channels created with this function.
Beware that input channels are buffered, so more characters may have been read from the descriptor than those accessed using channel functions. Channels also keep a copy of the current position in the file.
Closing the channel ic
returned by in_channel_of_descr fd
using close_in ic
also closes the underlying descriptor fd
. It is incorrect to close both the channel ic
and the descriptor fd
.
If several channels are created on the same descriptor, one of the channels must be closed, but not the others. Consider for example a descriptor s
connected to a socket and two channels ic = in_channel_of_descr s
and oc = out_channel_of_descr s
. The recommended closing protocol is to perform close_out oc
, which flushes buffered output to the socket then closes the socket. The ic
channel must not be closed and will be collected by the GC eventually.
val out_channel_of_descr : file_descr -> out_channel
Create an output channel writing on the given descriptor. The channel is initially in binary mode; use set_binary_mode_out oc false
if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.
On Windows: Stdlib.set_binary_mode_out
always fails on channels created with this function.
Beware that output channels are buffered, so you may have to call Stdlib.flush
to ensure that all data has been sent to the descriptor. Channels also keep a copy of the current position in the file.
Closing the channel oc
returned by out_channel_of_descr fd
using close_out oc
also closes the underlying descriptor fd
. It is incorrect to close both the channel ic
and the descriptor fd
.
See Unix.in_channel_of_descr
for a discussion of the closing protocol when several channels are created on the same descriptor.
val descr_of_in_channel : in_channel -> file_descr
Return the descriptor corresponding to an input channel.
val descr_of_out_channel : out_channel -> file_descr
Return the descriptor corresponding to an output channel.
Seeking and truncating
type seek_command =
Positioning modes for lseek
.
val lseek : file_descr -> int -> seek_command -> int
Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file).
val ftruncate : file_descr -> int -> unit
Truncates the file corresponding to the given descriptor to the given size.
File status
type stats = {
st_dev : int; | (* Device number *) |
st_ino : int; | (* Inode number *) |
st_kind : file_kind; | (* Kind of the file *) |
st_perm : file_perm; | (* Access rights *) |
st_nlink : int; | (* Number of links *) |
st_uid : int; | (* User id of the owner *) |
st_gid : int; | (* Group ID of the file's group *) |
st_rdev : int; | (* Device ID (if special file) *) |
st_size : int; | (* Size in bytes *) |
st_atime : float; | (* Last access time *) |
st_mtime : float; | (* Last modification time *) |
st_ctime : float; | (* Last status change time *) |
}
The information returned by the stat
calls.
val stat : string -> stats
Return the information for the named file.
val lstat : string -> stats
Same as stat
, but in case the file is a symbolic link, return the information for the link itself.
val fstat : file_descr -> stats
Return the information for the file associated with the given descriptor.
val isatty : file_descr -> bool
Return true
if the given file descriptor refers to a terminal or console window, false
otherwise.
File operations on large files
module LargeFile : sig ... end
File operations on large files. This sub-module provides 64-bit variants of the functions lseek
(for positioning a file descriptor), truncate
and ftruncate
(for changing the size of a file), and stat
, lstat
and 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
.
Mapping files into memory
val map_file :
file_descr ->
?pos:int64 ->
( 'a, 'b ) Bigarray.kind ->
'c Bigarray.layout ->
bool ->
int array ->
( 'a, 'b, 'c ) Bigarray.Genarray.t
Memory mapping of a file as a Bigarray. map_file fd kind layout shared dims
returns a Bigarray of kind kind
, layout layout
, and dimensions as specified in dims
. The data contained in this Bigarray are the contents of the file referred to by the file descriptor fd
(as opened previously with openfile
, for example). The optional pos
parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file).
If shared
is true
, all modifications performed on the array are reflected in the file. This requires that fd
be opened with write permissions. If shared
is false
, modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected.
Genarray.map_file
is much more efficient than reading the whole file in a Bigarray, modifying that Bigarray, and writing it afterwards.
To adjust automatically the dimensions of the Bigarray to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as -1
. Genarray.map_file
then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise Failure
is raised.
If all dimensions of the Bigarray are given, the file size is matched against the size of the Bigarray. If the file is larger than the Bigarray, only the initial portion of the file is mapped to the Bigarray. If the file is smaller than the big array, the file is automatically grown to the size of the Bigarray. This requires write permissions on fd
.
Array accesses are bounds-checked, but the bounds are determined by the initial call to map_file
. Therefore, you should make sure no other process modifies the mapped file while you're accessing it, or a SIGBUS signal may be raised. This happens, for instance, if the file is shrunk.
Invalid_argument
or Failure
may be raised in cases where argument validation fails.
Operations on file names
Removes the named file.
If the named file is a directory, raises:
EPERM
on POSIX compliant systemEISDIR
on Linux >= 2.1.132EACCESS
on Windows
rename src dst
changes the name of a file from src
to dst
, moving it between directories if needed. If dst
already exists, its contents will be replaced with those of src
. Depending on the operating system, the metadata (permissions, owner, etc) of dst
can either be preserved or be replaced by those of src
.
link ?follow src dst
creates a hard link named dst
to the file named src
.
realpath p
is an absolute pathname for p
obtained by resolving all extra /
characters, relative path segments and symbolic links.
File permissions and ownership
type access_permission =
| R_OK | (* Read permission *) |
| W_OK | (* Write permission *) |
| X_OK | (* Execution permission *) |
| F_OK | (* File exists *) |
Flags for the access
call.
val chmod : string -> file_perm -> unit
Change the permissions of the named file.
val fchmod : file_descr -> file_perm -> unit
Change the permissions of an opened file.