ocaml-base-compiler

Official release 4.14.0
back to documentation root
Legend:
Library
Module
Module type
Parameter
Class
Class type
Library unix
Module Unix

Error report

type error =
| E2BIG(*

Argument list too long

*)
| EACCES(*

Permission denied

*)
| EAGAIN(*

Resource temporarily unavailable; try again

*)
| EBADF(*

Bad file descriptor

*)
| EBUSY(*

Resource unavailable

*)
| ECHILD(*

No child process

*)
| EDEADLK(*

Resource deadlock would occur

*)
| EDOM(*

Domain error for math functions, etc.

*)
| EEXIST(*

File exists

*)
| EFAULT(*

Bad address

*)
| EFBIG(*

File too large

*)
| EINTR(*

Function interrupted by signal

*)
| EINVAL(*

Invalid argument

*)
| EIO(*

Hardware I/O error

*)
| EISDIR(*

Is a directory

*)
| EMFILE(*

Too many open files by the process

*)
| ENAMETOOLONG(*

Filename too long

*)
| ENFILE(*

Too many open files in the system

*)
| ENODEV(*

No such device

*)
| ENOENT(*

No such file or directory

*)
| ENOEXEC(*

Not an executable file

*)
| ENOLCK(*

No locks available

*)
| ENOMEM(*

Not enough memory

*)
| ENOSPC(*

No space left on device

*)
| ENOSYS(*

Function not supported

*)
| ENOTDIR(*

Not a directory

*)
| ENOTEMPTY(*

Directory not empty

*)
| ENOTTY(*

Inappropriate I/O control operation

*)
| ENXIO(*

No such device or address

*)
| EPERM(*

Operation not permitted

*)
| EPIPE(*

Broken pipe

*)
| ERANGE(*

Result too large

*)
| EROFS(*

Read-only file system

*)
| ESPIPE(*

Invalid seek e.g. on a pipe

*)
| ESRCH(*

No such process

*)
| EXDEV(*

Invalid link

*)
| EWOULDBLOCK(*

Operation would block

*)
| EINPROGRESS(*

Operation now in progress

*)
| EALREADY(*

Operation already in progress

*)
| ENOTSOCK(*

Socket operation on non-socket

*)
| EDESTADDRREQ(*

Destination address required

*)
| EMSGSIZE(*

Message too long

*)
| EPROTOTYPE(*

Protocol wrong type for socket

*)
| ENOPROTOOPT(*

Protocol not available

*)
| EPROTONOSUPPORT(*

Protocol not supported

*)
| ESOCKTNOSUPPORT(*

Socket type not supported

*)
| EOPNOTSUPP(*

Operation not supported on socket

*)
| EPFNOSUPPORT(*

Protocol family not supported

*)
| EAFNOSUPPORT(*

Address family not supported by protocol family

*)
| EADDRINUSE(*

Address already in use

*)
| EADDRNOTAVAIL(*

Can't assign requested address

*)
| ENETDOWN(*

Network is down

*)
| ENETUNREACH(*

Network is unreachable

*)
| ENETRESET(*

Network dropped connection on reset

*)
| ECONNABORTED(*

Software caused connection abort

*)
| ECONNRESET(*

Connection reset by peer

*)
| ENOBUFS(*

No buffer space available

*)
| EISCONN(*

Socket is already connected

*)
| ENOTCONN(*

Socket is not connected

*)
| ESHUTDOWN(*

Can't send after socket shutdown

*)
| ETOOMANYREFS(*

Too many references: can't splice

*)
| ETIMEDOUT(*

Connection timed out

*)
| ECONNREFUSED(*

Connection refused

*)
| EHOSTDOWN(*

Host is down

*)
| EHOSTUNREACH(*

No route to host

*)
| ELOOP(*

Too many levels of symbolic links

*)
| EOVERFLOW(*

File size or position not representable

*)
| EUNKNOWNERR of int(*

Unknown 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.

val handle_unix_error : ( 'a -> 'b ) -> 'a -> 'b

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''. The returned array is empty if the process has special privileges.

val unsafe_environment : unit -> string array

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.

  • since 4.06.0 (4.12.0 in UnixLabels)
val getenv : string -> string

Return the value associated to a variable in the process environment, unless the process has special privileges.

  • raises Not_found

    if the variable is unbound or the process has special privileges.

    This function is identical to Sys.getenv.

val unsafe_getenv : string -> string

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.

  • raises Not_found

    if the variable is unbound.

  • since 4.06.0
val putenv : string -> string -> unit

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 =
| WEXITED of int(*

The process terminated normally by exit; the argument is the return code.

*)
| WSIGNALED of int(*

The process was killed by a signal; the argument is the signal number.

*)
| WSTOPPED of 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.

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.

val execv : string -> string array -> 'a

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.

  • raises Unix_error

    on failure

val execve : string -> string array -> string array -> 'a

Same as execv, except that the third argument provides the environment to the program executed.

val execvp : string -> string array -> 'a

Same as execv, except that the program is searched in the path.

val execvpe : string -> string array -> string array -> 'a

Same as execve, except that the program is searched in the path.

val fork : unit -> int

Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process.

  • raises Invalid_argument

    on Windows. Use create_process or threads instead.

val wait : unit -> int * process_status

Wait until one of the children processes die, and return its pid and termination status.

  • raises Invalid_argument

    on Windows. Use waitpid instead.

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.

val _exit : int -> 'a

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.

  • since 4.12.0
val getpid : unit -> int

Return the pid of the process.

val getppid : unit -> int

Return the pid of the parent process.

  • raises Invalid_argument

    on Windows (because it is meaningless)

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.

  • raises Invalid_argument

    on Windows

Basic file input/output

type file_descr

The abstract type of file descriptors.

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 openfile. See set_close_on_exec for more information.

*)
| O_KEEPEXEC(*

Clear the close-on-exec flag. This is currently the default.

*)

The flags to openfile.

type file_perm = int

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.

  • since 4.08.0 (4.12.0 in UnixLabels)
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.

  • since 4.02.0
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.

  • since 4.02.0

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 =
| SEEK_SET(*

indicates positions relative to the beginning of the file

*)
| SEEK_CUR(*

indicates positions relative to the current position

*)
| SEEK_END(*

indicates positions relative to the end of the file

*)

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 truncate : string -> int -> unit

Truncates the named file to the given size.

val ftruncate : file_descr -> int -> unit

Truncates the file corresponding to the given descriptor to the given size.

File status

type file_kind =
| S_REG(*

Regular file

*)
| S_DIR(*

Directory

*)
| S_CHR(*

Character device

*)
| S_BLK(*

Block device

*)
| S_LNK(*

Symbolic link

*)
| S_FIFO(*

Named pipe

*)
| S_SOCK(*

Socket

*)
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_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.

  • since 4.06.0

Operations on file names

Removes the named file.

If the named file is a directory, raises:

  • EPERM on POSIX compliant system
  • EISDIR on Linux >= 2.1.132
  • EACCESS on Windows
val rename : string -> string -> unit

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.

  • parameter follow

    indicates whether a src symlink is followed or a hardlink to src itself will be created. On Unix systems this is done using the linkat(2) function. If ?follow is not provided, then the link(2) function is used whose behaviour is OS-dependent, but more widely available.

  • raises ENOSYS

    On Unix if ~follow:_ is requested, but linkat is unavailable.

  • raises ENOSYS

    On Windows if ~follow:false is requested.

val realpath : string -> string

realpath p is an absolute pathname for p obtained by resolving all extra / characters, relative path segments and symbolic links.

  • since 4.13.0

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.

  • raises Invalid_argument

    on Windows

val chown : string -> int -> int -> unit

Change the owner uid and owner gid of the named file.