UnixLabels(3)

๐ŸŒธ NAME ๐ŸŒธ

UnixLabels โ€” interface to the Unix system ๐Ÿ’…

Like, this whole page is the UnixLabels module, which is literally the Unix module but with labels, and honestly? It's giving "same energy, better ergonomics" โœจ


๐ŸŽ€ Module ๐ŸŽ€

Module UnixLabels ๐Ÿซถ


๐Ÿ“– Documentation ๐Ÿ“–

Module UnixLabels : sig end โ€” the actual interface to the Unix system, bestie ๐Ÿ’–

So here's the move: if you want the labeled version of this module, you just drop

module Unix = UnixLabels

into your implementation and you're so back ๐Ÿ‘‘ (that's literally what the manpage tells you to do, iykyk).

โš ๏ธ Big heads-up, no cap: all the functions in this module โ€” every single one โ€” are liable to raise the UnixLabels.Unix_error exception whenever the underlying system call signals an error. The only two exceptions to that rule are UnixLabels.error_message and UnixLabels.handle_unix_error. That's it. Those two. Everyone else can and will throw at you ๐Ÿ˜ญ

๐Ÿซถ Error report ๐Ÿซถ

First thing in this section is the error type, and it's a big one:

type error = Unix.error =

and then the constructors, which I'm gonna list out for you because there are so many and you deserve to know all of them ๐Ÿ’€

  • 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
  • EMLINK โ€” too many links
  • 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 โ“

So that's the type of error codes, periodt. Fun fact: the errors defined in the POSIX standard plus the extra errors from UNIX98 and BSD all live here. Everything else โ€” literally any other error โ€” gets mapped to EUNKNOWNERR. That's the catch-all bin, bestie ๐Ÿ—‘๏ธ


  • exception Unix_error of error * string * string โ€” this is the icon ๐Ÿ’… It gets raised by all the system calls below whenever an error is encountered. The first component is the error code, the second component is the function name, and the third component is the string parameter to the function if it has one, or the empty string otherwise. And here's the slay detail: UnixLabels.Unix_error and Unix.Unix_error are literally the same thing, so catching one catches the other ๐Ÿซถ
  • val error_message : error -> string โ€” hand it an error code, it hands you back a string describing that error code. Simple as that โœจ
  • val handle_unix_error : ('a -> 'b) -> 'a -> 'b โ€” so handle_unix_error f x applies f to x and returns the result. But if the exception UnixLabels.Unix_error gets raised, it prints a message describing the error and then exits with code 2. Iconic behaviour ngl ๐Ÿ‘‘

๐Ÿฆ‹ Access to the process environment ๐Ÿฆ‹

  • val environment : unit -> string array โ€” returns the process environment as an array of strings formatted like variable=value. But heads-up: the returned array is empty if the process has special privileges ๐Ÿ‘€
  • val unsafe_environment : unit -> string array โ€” same deal, returns the process environment as an array of strings formatted variable=value, but unlike UnixLabels.environment, this one returns a populated array even if the process has special privileges ๐Ÿ˜ณ See the documentation for UnixLabels.unsafe_getenv for more details. Since 4.12
  • val getenv : string -> string โ€” returns 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. Also it's identical to Sys.getenv ๐ŸŽ€
  • val unsafe_getenv : string -> string โ€” returns the value associated to a variable in the process environment. Unlike UnixLabels.getenv, this one returns the value even if the process has special privileges. And why's it called unsafe? Because the programmer of a setuid or setgid program has to 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 ๐Ÿšจ So like, respect the name fr fr. Since 4.06. Raises Not_found if the variable is unbound.
  • 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 is its new associated value ๐Ÿ’–
  • val unsetenv : string -> unit โ€” unsetenv name removes the variable name from the process environment ๐Ÿซง Since 5.5

๐Ÿ”ฅ Process handling ๐Ÿ”ฅ

  • type process_status = Unix.process_status = โ€” the termination status of a process, and it's got three flavors:
    • WEXITED of int โ€” the process terminated normally by exit; the argument is the return code โœ…
    • WSIGNALED of Sys.signal โ€” the process was killed by a signal; the argument is the signal number ๐Ÿ’€
    • WSTOPPED of Sys.signal โ€” the process was stopped by a signal; the argument is the signal number โœ‹

See Sys.signal for the definitions of the standard signal numbers.

๐ŸชŸ On Windows: only WEXITED is used (since there are no inter-process signals) but with specific return codes to indicate special termination causes. Look for NTSTATUS values in the Windows documentation to decode such error return codes. In particular, the STATUS_ACCESS_VIOLATION error code is the 32-bit 0xC0000005: as Int32.of_int 0xC0000005 is -1073741819, WEXITED -1073741819 is the Windows equivalent of WSIGNALED Sys.sigsegv. Like, that's the whole mapping, bestie ๐Ÿง 
  • type wait_flag = Unix.wait_flag = โ€” flags for UnixLabels.waitpid:
    • 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 โœ‹

  • val execv : prog:string -> args:string array -> 'a โ€” execv prog args executes the program in file prog, with the arguments args, and the current process environment. Quick note: the first argument, args.(0), is by convention the filename of the program being executed, just like Sys.argv.(0) ๐Ÿ‘‘ And these execv* functions never return: on success, the current program is replaced by the new one. So yeah, that's the whole bit ๐Ÿ’…
๐ŸชŸ On Windows: the CRT simply spawns a new process and exits the current one. This will have unwanted consequences if e.g. another process is waiting on the current one. Using UnixLabels.create_process or one of the open_process_* functions instead is recommended ๐Ÿ™

Raises Unix_error on failure.

  • val execve : prog:string -> args:string array -> env:string array -> 'a โ€” same as UnixLabels.execv, except that the third argument provides the environment to the program executed ๐ŸŒ
  • val execvp : prog:string -> args:string array -> 'a โ€” same as UnixLabels.execv, except that the program is searched in the path ๐Ÿ”
  • val execvpe : prog:string -> args:string array -> env:string array -> 'a โ€” same as UnixLabels.execve, except that the program is searched in the path ๐Ÿ”
  • val fork : unit -> int โ€” forks a new process, classic. The returned integer is 0 for the child process, and the pid of the child process for the parent process ๐Ÿ‘ถ It fails if the OCaml process is multi-core (i.e. if any domain has been spawned). And on top of that, if any thread from the Thread module has been spawned, then the child process might be in a corrupted state ๐Ÿ˜ญ so be careful. Raises Invalid_argument on Windows โ€” use UnixLabels.create_process or threads instead. Raises Failure if any domain has been spawned.
  • val wait : unit -> int * process_status โ€” waits until one of the children processes dies, and returns its pid and termination status โณ Raises Invalid_argument on Windows โ€” use UnixLabels.waitpid instead.
  • val waitpid : mode:wait_flag list -> int -> int * process_status โ€” same as UnixLabels.wait, but it 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. Noted ๐Ÿ’€
  • val system : string -> process_status โ€” โ€ฆand that's where part 1 runs out of page, bestie, so hold that thought ๐Ÿ’ซ

โ€ฆso here's the whole deal: it runs that command, chills until it finishes, then hands you back its termination status. The string gets interpreted by the shell /bin/sh (or, on Windows, by the command interpreter cmd.exe), which means it can absolutely contain redirections, quotes, variables, all of it. ๐Ÿ’…

โš ๏ธ If file names or command arguments have whitespace or shell special characters in them, bestie, please use Filename.quote_command to quote them properly. Do not rawdog it. ๐Ÿ˜ญ

Oh and one iconic little detail: a result of WEXITED 127 means the shell itself couldn't be executed. That's the vibe check failing, not the command. ๐Ÿ’€


  • val _exit : int -> 'a โ€” Terminate the calling process immediately, returning the given status code to the operating system: usually 0 for "no errors" and a small positive integer for "yeah that failed".
๐Ÿšจ Unlike exit, Unix._exit performs no finalization whatsoever โ€” functions registered with at_exit are not called, input/output channels are not flushed, and the C run-time system is not finalized either. It just leaves. Zero goodbyes. Periodt.

The classic use of Unix._exit is right after a Unix.fork, when the child process hits a fatal error and has to bail. In that situation you genuinely want no finalization in the child, because those actions could mess with similar actions the parent is doing. Like, for real: output channels should not be flushed by the child, because the parent might flush them again later and you'd get duplicate output. ๐Ÿ™ˆ

Since 4.12

  • val getpid : unit -> int โ€” Returns the pid of the process. That's it. That's the whole function. ๐Ÿซถ
  • val getppid : unit -> int โ€” Returns the pid of the parent process.

Raises Invalid_argument on Windows (because it is meaningless there).

  • val nice : int -> int โ€” Changes the process priority. The integer argument gets added to the nice'' value. (Higher nice'' values = lower priorities, which is lowkey the most confusing naming convention ever but okay.) Returns the new nice value. ๐Ÿ’œ

Raises Invalid_argument on Windows.


๐Ÿ’– Basic file input/output ๐Ÿ’–

type file_descr = Unix.file_descr

The abstract type of file descriptors. Fancy little handles, basically.

  • 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 = Unix.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 UnixLabels.openfile. See UnixLabels.set_close_on_exec for more information.
  • O_KEEPEXEC โ€” Clear the close-on-exec flag. This is currently the default.

Those are the flags to UnixLabels.openfile, bestie. โœจ

type file_perm = int

The type of file access rights โ€” like, 0o640 is read and write for user, read for group, and absolutely nothing for others. ๐ŸŒธ

  • val openfile : string -> mode:open_flag list -> perm:file_perm -> file_descr โ€” Opens the named file with the given flags. Third argument is the permissions to give to the file if it is created (see UnixLabels.umask). Returns a file descriptor on the named file. ๐ŸŽ€
  • val close : file_descr -> unit โ€” Closes a file descriptor. Say bye ๐Ÿ‘‹
  • val fsync : file_descr -> unit โ€” Flushes file buffers to disk. The "no seriously, actually write it" button.

Since 4.12

  • val read : file_descr -> buf:bytes -> pos:int -> len:int -> int โ€” read fd ~buf ~pos ~len reads len bytes from descriptor fd, stores them in byte sequence buf, starting at position pos in buf. Returns the number of bytes actually read. ๐Ÿฆ‹
  • val read_bigarray : file_descr -> buf:('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t -> pos:int -> len:int -> int โ€” Same as UnixLabels.read, but it reads the data into a bigarray.

Since 5.2

  • val write : file_descr -> buf:bytes -> pos:int -> len:int -> int โ€” write fd ~buf ~pos ~len writes len bytes to descriptor fd, taking them from byte sequence buf, starting at position pos in buf. Returns the number of bytes actually written. Important: write repeats the writing operation until all bytes have been written or an error occurs โ€” it's committed like that. ๐Ÿ’…
  • val write_bigarray : file_descr -> buf:('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t -> pos:int -> len:int -> int โ€” Same as UnixLabels.write, but it takes the data from a bigarray.

Since 5.2

  • val single_write : file_descr -> buf:bytes -> pos:int -> len:int -> int โ€” Same as UnixLabels.write, but it attempts to write only once. So if an error occurs, single_write guarantees that no data has been written. Iconic all-or-nothing behaviour. ๐Ÿ”ฅ
  • val write_substring : file_descr -> buf:string -> pos:int -> len:int -> int โ€” Same as UnixLabels.write, but takes the data from a string instead of a byte sequence.

Since 4.02

  • val single_write_substring : file_descr -> buf:string -> pos:int -> len:int -> int โ€” Same as UnixLabels.single_write, but takes the data from a string instead of a byte sequence.

Since 4.02

  • val single_write_bigarray : file_descr -> buf:('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t -> pos:int -> len:int -> int โ€” Same as UnixLabels.single_write, but takes the data from a bigarray.

Since 5.2


๐Ÿงš Interfacing with the standard input/output library ๐Ÿงš

  • val in_channel_of_descr : file_descr -> in_channel โ€” Creates an input channel reading from the given descriptor.

The channel starts out in binary mode; use set_binary_mode_in ic false if you want text mode. Text mode is only supported if the descriptor refers to a file or pipe โ€” it is not supported if it refers to a socket.

๐ŸชŸ On Windows: set_binary_mode_in always fails on channels created with this function.

Beware, bestie: input channels are buffered, so more characters may have been read from the descriptor than the ones you actually accessed with channel functions. Channels also keep their own copy of the current position in the file. ๐Ÿ˜ญ

Closing the channel ic returned by in_channel_of_descr fd with close_in ic also closes the underlying descriptor fd. It is incorrect to close both the channel ic and the descriptor fd. Pick one. ๐Ÿ’€

If several channels get created on the same descriptor, one of the channels must be closed โ€” but not the others. 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 do close_out oc, which flushes buffered output to the socket and then closes the socket. The ic channel must not be closed and will be collected by the GC eventually. Let the garbage collector have its moment. โœจ

  • val out_channel_of_descr : file_descr -> out_channel โ€” Creates an output channel writing on the given descriptor.

The channel starts out in binary mode; use set_binary_mode_out oc false if text mode is what you want. Text mode is supported only if the descriptor refers to a file or pipe, and is not supported if it refers to a socket.

๐ŸชŸ On Windows: set_binary_mode_out always fails on channels created with this function.

Beware that output channels are buffered, so you may have to call flush to make sure all the data actually got 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 with 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 the discussion of the closing protocol when several channels are created on the same descriptor. ๐Ÿ‘‘

  • val descr_of_in_channel : in_channel -> file_descr โ€” Returns the descriptor corresponding to an input channel.
  • val descr_of_out_channel : out_channel -> file_descr โ€” Returns the descriptor corresponding to an output channel.

๐ŸŽ€ Seeking and truncating ๐ŸŽ€

type seek_command = Unix.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

These are the positioning modes for UnixLabels.lseek. ๐ŸŒˆ

  • val lseek : file_descr -> int -> mode:seek_command -> int โ€” Sets the current position for a file descriptor and returns the resulting offset (from the beginning of the file).
  • val truncate : string -> len:int -> unit โ€” Truncates the named file to the given size.
  • val ftruncate : file_descr -> len:int -> unit โ€” Truncates the file corresponding to the given descriptor to the given size.

โญ File status โญ

type file_kind = Unix.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 = Unix.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

}

That whole record is the info you get back from the UnixLabels.stat calls. ๐Ÿ“

  • val stat : string -> stats โ€” Returns the information for the named file.
  • val lstat : string -> stats โ€” Same as UnixLabels.stat, but if the file is a symbolic link, it returns the information for the link itself. Iconic "look at me, not through me" energy. ๐Ÿ’…
  • val fstat : file_descr -> stats โ€” Returns the information for the file associated with the given descriptor.
  • val isatty : file_descr -> bool โ€” Returns true if the given file descriptor refers to a terminal or console window, false otherwise.

๐Ÿฆ‹ File operations on large files ๐Ÿฆ‹

module LargeFile : sig end

Okay so, file operations on large files โ€” this sub-module provides 64-bit variants of UnixLabels.LargeFile.lseek (for positioning a file descriptor), UnixLabels.LargeFile.truncate and UnixLabels.LargeFile.ftruncate (for changing the size of a file), and UnixLabels.LargeFile.stat, UnixLabels.LargeFile.lstat and UnixLabels.LargeFile.fstat (for getting info on files). These alternate functions represent positions and sizes by 64-bit integers (type int64) instead of regular integers (type int), so yeah, you can operate on files whose sizes are greater than max_int. ๐Ÿ’…

๐Ÿ—บ๏ธ Mapping files into memory

val map_file : file_descr -> ?pos:int64 -> kind:('a, 'b) Bigarray.kind
-> layout:'c Bigarray.layout -> shared:bool -> dims: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 UnixLabels.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. ๐Ÿซถ

UnixLabels.map_file is much more efficient than reading the whole file in a Bigarray, modifying that Bigarray, and writing it afterwards. Obsessed, honestly.

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

bestie, pay attention here: 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.

๐Ÿ—‚๏ธ Operations on file names

  • val unlink : string -> unit โ€” 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 : src:string -> dst: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.
  • val link : ?follow:bool -> src:string -> dst:string -> unit โ€” link ?follow ~src ~dst creates a hard link named dst to the file named src.

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.

๐Ÿ” File permissions and ownership

type access_permission = Unix.access_permission =
 | R_OK  (* Read permission
 *)
 | W_OK  (* Write permission
 *)
 | X_OK  (* Execution permission
 *)
 | F_OK  (* File exists
 *)

Flags for the UnixLabels.access call.

  • val chmod : string -> perm:file_perm -> unit โ€” change the permissions of the named file.
  • val fchmod : file_descr -> perm:file_perm -> unit โ€” change the permissions of an opened file.
    • Raises Invalid_argument on Windows.
  • val chown : string -> uid:int -> gid:int -> unit โ€” change the owner uid and owner gid of the named file.
    • Raises Invalid_argument on Windows.
  • val fchown : file_descr -> uid:int -> gid:int -> unit โ€” change the owner uid and owner gid of an opened file.
    • Raises Invalid_argument on Windows.
  • val umask : file_perm -> file_perm โ€” set the process's file mode creation mask, and return the previous mask.
    • Raises Invalid_argument on Windows.
  • val access : string -> perm:access_permission list -> unit โ€” check that the process has the given permissions over the named file.

On Windows: execute permission X_OK cannot be tested, just tests for read permission instead.

Raises Unix_error otherwise.

๐Ÿงฌ Operations on file descriptors

  • val dup : ?cloexec:bool -> file_descr -> file_descr โ€” return a new file descriptor referencing the same file as the given descriptor. See UnixLabels.set_close_on_exec for documentation on the cloexec optional argument.
  • val dup2 : ?cloexec:bool -> src:file_descr -> dst:file_descr -> unit โ€” dup2 ~src ~dst duplicates src to dst, closing dst if already opened. See UnixLabels.set_close_on_exec for documentation on the cloexec optional argument.
  • val set_nonblock : file_descr -> unit โ€” 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 the 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.
  • val clear_nonblock : file_descr -> unit โ€” clear the non-blocking flag on the given descriptor. See UnixLabels.set_nonblock.
  • val set_close_on_exec : file_descr -> unit โ€” 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, create_process and open_process functions.

It is often a security hole to leak file descriptors opened on, say, a private file to an external program: the program, then, gets access to the private file and can do bad things with it. Hence, it is highly recommended to set all file descriptors close-on-exec, except in the very few cases where a file descriptor actually needs to be transmitted to another program. ๐Ÿšจ

The best way to set a file descriptor close-on-exec is to create it in this state. To this end, the openfile function has O_CLOEXEC and O_KEEPEXEC flags to enforce close-on-exec mode or keep-on-exec mode, respectively. All other operations in the Unix module that create file descriptors have an optional argument ?cloexec:bool to indicate whether the file descriptor should be created in close-on-exec mode (by writing ~cloexec:true) or in keep-on-exec mode (by writing ~cloexec:false). For historical reasons, the default file descriptor creation mode is keep-on-exec, if no cloexec optional argument is given. This is not a safe default, hence it is highly recommended to pass explicit cloexec arguments to operations that create file descriptors. ๐Ÿ’ฏ

The cloexec optional arguments and the O_KEEPEXEC flag were introduced in OCaml 4.05. Earlier, the common practice was to create file descriptors in the default, keep-on-exec mode, then call set_close_on_exec on those freshly-created file descriptors. This is not as safe as creating the file descriptor in close-on-exec mode because, in multithreaded programs, a window of vulnerability exists between the time when the file descriptor is created and the time set_close_on_exec completes. If another thread spawns another program during this window, the descriptor will leak, as it is still in the keep-on-exec mode.

Regarding the atomicity guarantees given by ~cloexec:true or by the use of the O_CLOEXEC flag: on all platforms it is guaranteed that a concurrently-executing Caml thread cannot leak the descriptor by starting a new process. On Linux, this guarantee extends to concurrently-executing C threads. As of Feb 2017, other operating systems lack the necessary system calls and still expose a window of vulnerability during which a C thread can see the newly-created file descriptor in keep-on-exec mode.

  • val clear_close_on_exec : file_descr -> unit โ€” clear the close-on-exec flag on the given descriptor. See UnixLabels.set_close_on_exec.

๐Ÿ“ Directories

  • val mkdir : string -> perm:file_perm -> unit โ€” create a directory with the given permissions (see UnixLabels.umask).
  • val rmdir : string -> unit โ€” remove an empty directory.
  • val chdir : string -> unit โ€” change the process working directory.
  • val getcwd : unit -> string โ€” return the name of the current working directory.
  • val chroot : string -> unit โ€” change the process root directory.
    • Raises Invalid_argument on Windows.
  • type dir_handle = Unix.dir_handle โ€” the type of descriptors over opened directories.
  • val opendir : string -> dir_handle โ€” open a descriptor on a directory.
  • val readdir : dir_handle -> string โ€” return the next entry in a directory.
    • Raises End_of_file when the end of the directory has been reached.
  • val rewinddir : dir_handle -> unit โ€” reposition the descriptor to the beginning of the directory.
  • val closedir : dir_handle -> unit โ€” close a directory descriptor.

๐Ÿšฐ Pipes and redirections

  • val pipe : ?cloexec:bool -> unit -> file_descr * file_descr โ€” 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. See UnixLabels.set_close_on_exec for documentation on the cloexec optional argument.
  • val mkfifo : string -> perm:file_perm -> unit โ€” create a named pipe with the given permissions (see UnixLabels.umask).
    • Raises Invalid_argument on Windows.

๐ŸŽ›๏ธ High-level process and redirection management

val create_process : prog:string -> args:string array ->
stdin:file_descr -> stdout:file_descr -> stderr:file_descr -> int
val create_process : prog:string -> args:string array -> stdin:file_descr -> stdout:file_descr -> stderr:file_descr -> int

create_process ~prog ~args ~stdin ~stdout ~stderr is literally the "go make a whole new process" button, bestie ๐Ÿซถ It spawns a fresh process that runs the program in file prog, with arguments args. Heads up tho: the first argument, args.(0), is by convention the filename of the program being executed โ€” exactly like Sys.argv.(0). Iconic consistency, we love to see it โœจ

The pid of the new process comes back to you immediately, and the new process runs concurrently with the current one (so yes, two things happening at once, main character energy for both ๐Ÿ’…). The standard input and outputs of the new process get hooked up to the descriptors stdin, stdout and stderr.

Wanna skip the redirect on one of them? Pass e.g. Unix.stdout for stdout โ€” that prevents the redirection and the new process just inherits the same standard output as the current process. Neat ๐ŸŽ€

The executable file prog is searched in the path. And the new process has the same environment as the current process.

val create_process_env : prog:string -> args:string array -> env:string array -> stdin:file_descr -> stdout:file_descr -> stderr:file_descr -> int

create_process_env ~prog ~args ~env ~stdin ~stdout ~stderr works exactly like UnixLabels.create_process, except the extra argument env specifies the environment passed to the program. Custom env, custom vibe ๐ŸŒˆ

val open_process_in : string -> in_channel

High-level pipe and process management, let's gooo ๐Ÿ”ฅ This function runs the given command in parallel with the program. The standard output of the command is redirected to a pipe, which you can read through the returned input channel.

The command is interpreted by the shell /bin/sh (or cmd.exe on Windows), cf. UnixLabels.system. And ooh, the Filename.quote_command function can be used to quote the command and its arguments as appropriate for whichever shell is being used โ€” very much the responsible-bestie move ๐Ÿ’–

If the command doesn't need to be run through the shell, UnixLabels.open_process_args_in can be used as a more robust and more efficient alternative to UnixLabels.open_process_in. Slay, less shell, fewer problems โœจ

val open_process_out : string -> out_channel

Same as UnixLabels.open_process_in, but redirect the standard input of the command to a pipe instead. Data written to the returned output channel is sent to the standard input of the command.

โš ๏ธ Warning: writes on output channels are buffered, so be careful to call flush at the right times to make sure everything stays in sync. This is the number one way to get a cursed debugging session, ngl ๐Ÿ˜ญ

If the command doesn't need to be run through the shell, UnixLabels.open_process_args_out can be used instead of UnixLabels.open_process_out.

val open_process : string -> in_channel * out_channel

Same as UnixLabels.open_process_out, but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. The input channel is connected to the output of the command, and the output channel to the input of the command. Two-way conversation, we're chatting ๐Ÿ’ฌ

If the command doesn't need to be run through the shell, UnixLabels.open_process_args can be used instead of UnixLabels.open_process.

val open_process_full : string -> env:string array -> in_channel * out_channel * in_channel

Similar to UnixLabels.open_process, but the second argument specifies the environment passed to the command. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the command. Three channels, three vibes ๐ŸŽ€

If the command doesn't need to be run through the shell, UnixLabels.open_process_args_full can be used instead of UnixLabels.open_process_full.

val open_process_args : string -> string array -> in_channel * out_channel

open_process_args prog args runs the program prog with arguments args. Again: the first argument, args.(0), is by convention the filename of the program being executed, just like Sys.argv.(0). The new process executes concurrently with the current process. Its standard input and output are redirected to pipes, which you can respectively read and write via the returned channels. The input channel is connected to the output of the program, and the output channel to the input of the program. ๐Ÿฆ‹

โš ๏ธ Warning: writes on output channels are buffered, hence be careful to call flush at the right times to ensure correct synchronization. (Yes I'm telling you twice, it's that important, bestie ๐Ÿ’€)

The executable file prog is searched for in the path. This behaviour changed in 4.12 โ€” previously prog was looked up only in the current directory. So if you're reading ancient code, that's the lore ๐Ÿ‘‘

The new process has the same environment as the current process.

Since 4.08

val open_process_args_in : string -> string array -> in_channel

Same as UnixLabels.open_process_args, but redirects only the standard output of the new process.

Since 4.08

val open_process_args_out : string -> string array -> out_channel

Same as UnixLabels.open_process_args, but redirects only the standard input of the new process.

Since 4.08

val open_process_args_full : string -> string array -> string array -> in_channel * out_channel * in_channel

Similar to UnixLabels.open_process_args, but the third argument specifies the environment passed to the new process. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the program. Full send ๐Ÿ’œ

Since 4.08

val process_in_pid : in_channel -> int

Returns the pid of a process opened via UnixLabels.open_process_args_in, or the pid of the shell opened via UnixLabels.open_process_in.

Since 4.12

val process_out_pid : out_channel -> int

Returns the pid of a process opened via UnixLabels.open_process_args_out, or the pid of the shell opened via UnixLabels.open_process_out.

Since 4.12

val process_pid : in_channel * out_channel -> int

Returns the pid of a process opened via UnixLabels.open_process_args, or the pid of the shell opened via UnixLabels.open_process_args.

Since 4.12

val process_full_pid : in_channel * out_channel * in_channel -> int

Returns the pid of a process opened via UnixLabels.open_process_args_full, or the pid of the shell opened via UnixLabels.open_process_full.

Since 4.12

val close_process_in : in_channel -> process_status

Closes channels opened by UnixLabels.open_process_in, waits for the associated command to terminate, and returns its termination status. Cleanup era ๐Ÿงนโœจ

val close_process_out : out_channel -> process_status

Closes channels opened by UnixLabels.open_process_out, waits for the associated command to terminate, and returns its termination status.

val close_process : in_channel * out_channel -> process_status

Closes channels opened by UnixLabels.open_process, waits for the associated command to terminate, and returns its termination status.

val close_process_full : in_channel * out_channel * in_channel -> process_status

Closes channels opened by UnixLabels.open_process_full, waits for the associated command to terminate, and returns its termination status.


val symlink : ?to_dir:bool -> src:string -> dst:string -> unit

symlink ?to_dir ~src ~dst creates the file dst as a symbolic link to the file src. On Windows, ~to_dir indicates if the symbolic link points to a directory or a file. If it's omitted, symlink examines src using stat and picks appropriately โ€” and if src doesn't exist, then false is assumed. (For this reason, it is recommended that the ~to_dir parameter be specified in new code. Do it. Future you says thank you ๐Ÿ™). On Unix, ~to_dir is ignored entirely, no thoughts, head empty ๐Ÿ’…

Windows symbolic links are available in Windows Vista onwards. But โ€” and this is the tea โ€” 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 that actually points to a file cannot be selected with chdir, and a file symlink that actually points to a directory cannot be read or written. (Note that Cygwin's emulation layer ignores this distinction โ€” Cygwin said "not my problem" ๐Ÿ’€)

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. That's when you gotta be specific, bestie ๐ŸŒธ

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. Gates, gates, gates ๐Ÿ”

UnixLabels.has_symlink can be used to check that a process is able to create symbolic links.

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 simply indicates that the symlink system call is available. A little vibe check for your permissions โœจ

Since 4.03

val readlink : string -> string

Read the contents of a symbolic link. That's it, that's the whole thing ๐Ÿซถ


๐Ÿ”ฎ Polling ๐Ÿ”ฎ

val select : read:file_descr list -> write:file_descr list -> except:file_descr list -> timeout:float -> file_descr list * file_descr list * file_descr list

Waits 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 โ€” and a negative fourth argument means no timeout (unbounded wait, we're waiting forever, ride or die ๐Ÿ˜ค).

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). Perfectly balanced, as all things should be โš–๏ธ

On Windows: if one of the descriptor lists exceeds FD_SETSIZE elements (64 by default), or if at least one non-socket file descriptor is used, the maximal timeout is capped to 2^32 milliseconds. Noted, Windows, we hear you ๐Ÿ™ˆ


๐Ÿ”’ Locking ๐Ÿ”’

type lock_command = Unix.lock_command =
 | F_ULOCK  (* Unlock a region
 *)
 | F_LOCK  (* Lock a region for writing, and block if already locked
 *)
 | F_TLOCK  (* Lock a region for writing, or fail if already locked
 *)
 | F_TEST  (* Test a region for other process locks
 *)
 | F_RLOCK  (* Lock a region for reading, and block if already locked
 *)
 | F_TRLOCK  (* Lock a region for reading, or fail if already locked
 *)

These are the commands for UnixLabels.lockf. Choose your fighter ๐ŸฅŠ

val lockf : file_descr -> mode:lock_command -> len:int -> unit

lockf fd ~mode ~len 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 UnixLabels.lseek), and extends len bytes forward if len is positive, len bytes backwards if len is negative, or all the way to the end of the file if len is zero. Flexible queen ๐Ÿ’…

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 โ€” sharing is caring, but only for reading ๐Ÿ“

The F_LOCK and F_TLOCK commands are here to try to slap a write lock on the specified region. The F_RLOCK and F_TRLOCK commands try to put a read lock on the specified region instead. If one or several locks put by another process prevent the current process from acquiring the lock, F_LOCK and F_RLOCK block until those locks are removed, while F_TLOCK and F_TRLOCK fail immediately with an exception. The F_ULOCK command removes whatever locks the current process has on the specified region. Finally, F_TEST checks whether a write lock can be acquired on the specified region, without actually putting a lock. It returns immediately if successful, or fails otherwise.

What happens when a process tries to lock a region of a file that is already locked by the same process? Okay so this is lowkey OS-dependent, bestie. On POSIX-compliant systems, the second lock operation succeeds and may "promote" the older lock from read lock to write lock. On Windows, the second lock operation will block or fail.


๐Ÿšจ Signals ๐Ÿšจ

Note: installation of signal handlers is performed via the functions Sys.signal and Sys.set_signal.
  • val kill : pid:int -> signal:Sys.signal -> unit โ€” kill ~pid ~signal sends signal number signal to the process with id pid.

On Windows: only the Sys.sigkill signal is emulated, causing the receiving process to exit with code ERROR_PROCESS_ABORTED (1067). Before OCaml 5.5, the receiving process exited with code 0.

type sigprocmask_command = Unix.sigprocmask_command =
  | SIG_SETMASK
  | SIG_BLOCK
  | SIG_UNBLOCK
  • val sigprocmask : mode:sigprocmask_command -> Sys.signal list -> Sys.signal list โ€” sigprocmask ~mode sigs changes the set of blocked signals. If mode is SIG_SETMASK, blocked signals are set to those in the list sigs. If mode is SIG_BLOCK, the signals in sigs are added to the set of blocked signals. If mode is SIG_UNBLOCK, the signals in sigs are removed from the set of blocked signals. sigprocmask returns the set of previously blocked signals.

Each domain, and each thread when the Thread module is loaded, has its own signal mask. sigprocmask only changes the mask of the current domain or current thread.

Raises Invalid_argument on Windows (no inter-process signals on Windows).

  • val sigpending : unit -> Sys.signal list โ€” returns the set of blocked signals that are currently pending.

Raises Invalid_argument on Windows (no inter-process signals on Windows).

  • val sigsuspend : Sys.signal 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.

Raises Invalid_argument on Windows (no inter-process signals on Windows).

  • val pause : unit -> unit โ€” waits until a non-ignored, non-blocked signal is delivered.

Raises Invalid_argument on Windows (no inter-process signals on Windows).

  • val sigwait : Sys.signal list -> Sys.signal โ€” sigwait sigs waits until one of the signals in the list sigs becomes pending. It then removes this signal from the set of pending signals, and returns the number of this signal. Signal handlers attached to the signals in sigs will not be invoked. The signals sigs are expected to be blocked before calling sigwait.

Since 5.4.

Raises Invalid_argument on Windows (no inter-process signals on Windows).

โฐ Time functions โฐ

type process_times = Unix.process_times = {
  tms_utime : float ;  (* User time for the process *)
  tms_stime : float ;  (* System time for the process *)
  tms_cutime : float ;  (* User time for the children processes *)
  tms_cstime : float ;  (* System time for the children processes *)
}

The execution times (CPU times) of a process.

type tm = Unix.tm = {
  tm_sec : int ;  (* Seconds 0..60 *)
  tm_min : int ;  (* Minutes 0..59 *)
  tm_hour : int ;  (* Hours 0..23 *)
  tm_mday : int ;  (* Day of month 1..31 *)
  tm_mon : int ;  (* Month of year 0..11 *)
  tm_year : int ;  (* Year - 1900 *)
  tm_wday : int ;  (* Day of week (Sunday is 0) *)
  tm_yday : int ;  (* Day of year 0..365 *)
  tm_isdst : bool ;  (* Daylight time savings in effect *)
}

The type representing wallclock time and calendar date.

  • val time : unit -> float โ€” returns the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.
  • val gettimeofday : unit -> float โ€” same as UnixLabels.time, but with resolution better than 1 second.
  • val gmtime : float -> tm โ€” converts a time in seconds, as returned by UnixLabels.time, into a date and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. To perform the inverse conversion, set the TZ environment variable to "UTC", use UnixLabels.mktime, and then restore the original value of TZ.
  • val localtime : float -> tm โ€” converts a time in seconds, as returned by UnixLabels.time, into a date and a time. Assumes the local time zone. The function performing the inverse conversion is UnixLabels.mktime.
  • val mktime : tm -> float * tm โ€” converts a date and time, specified by the tm argument, into a time in seconds, as returned by UnixLabels.time. The tm_isdst, tm_wday and tm_yday fields of tm are ignored. Also returns 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 โ€” schedules a SIGALRM signal after the given number of seconds.

Raises Invalid_argument on Windows.

  • val sleep : int -> unit โ€” stops execution for the given number of seconds.
  • val sleepf : float -> unit โ€” stops execution for the given number of seconds. Like sleep, but fractions of seconds are supported.

Since 4.12.

  • val times : unit -> process_times โ€” returns the execution times of the process.

On Windows: partially implemented, will not report timings for child processes.

  • val utimes : string -> access:float -> modif:float -> unit โ€” sets 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. If both times are 0.0, the access and last modification times are both set to the current time.
type interval_timer = Unix.interval_timer =
  | ITIMER_REAL  (* decrements in real time, and sends the signal SIGALRM when expired. *)
  | ITIMER_VIRTUAL  (* decrements in process virtual time, and sends SIGVTALRM when expired. *)
  | ITIMER_PROF  (* (for profiling) decrements both when the process is running and when the system is running on behalf of the process; it sends SIGPROF when expired. *)

The three kinds of interval timers.

type interval_timer_status = Unix.interval_timer_status = {
  it_interval : float ;  (* Period *)
  it_value : float ;  (* Current value of the timer *)
}

The type describing the status of an interval timer.

  • val getitimer : interval_timer -> interval_timer_status โ€” returns the current status of the given interval timer.

Raises Invalid_argument on Windows.

  • val setitimer : interval_timer -> interval_timer_status -> interval_timer_status โ€” 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 disables the timer. Setting s.it_interval to zero causes the timer to be disabled after its next expiration.

Raises Invalid_argument on Windows.

๐Ÿ‘ค User id, group id ๐Ÿ‘ค

  • val getuid : unit -> int โ€” returns the user id of the user executing the process.

On Windows: always returns 1.

  • val geteuid : unit -> int โ€” returns the effective user id under which the process runs.

On Windows: always returns 1.

  • val setuid : int -> unit โ€” sets the real user id and effective user id for the process.

Raises Invalid_argument on Windows.

  • val getgid : unit -> int โ€” returns the group id of the user executing the process.

On Windows: always returns 1.

  • val getegid : unit -> int โ€” returns the effective group id under which the process runs.

On Windows: always returns 1.

  • val setgid : int -> unit โ€” sets the real group id and effective group id for the process.

Raises Invalid_argument on Windows.

  • val getgroups : unit -> int array โ€” returns the list of groups to which the user executing the process belongs.

On Windows: always returns [|1|].

  • val setgroups : int array -> unit โ€” setgroups groups sets the supplementary group IDs for the calling process. Appropriate privileges are required.

Raises Invalid_argument on Windows.

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

Raises Invalid_argument on Windows.

type passwd_entry = Unix.passwd_entry = {
  pw_name : string ;
  pw_passwd : string ;
  pw_uid : int ;
  pw_gid : int ;
  pw_gecos : string ;
  pw_dir : string ;
  pw_shell : string ;
}

Structure of entries in the passwd database.

type group_entry = Unix.group_entry = {
  gr_name : string ;
  gr_passwd : string ;
  gr_gid : int ;
  gr_mem : string array ;
}

Structure of entries in the groups database.

  • val getlogin : unit -> string โ€” returns the login name of the user executing the process.
  • val getpwnam : string -> passwd_entry โ€” finds an entry in passwd with the given name.

Raises Not_found if no such entry exists, or always on Windows.

  • val getgrnam : string -> group_entry โ€” finds an entry in group with the given name.

Raises Not_found if no such entry exists, or always on Windows.

  • val getpwuid : int -> passwd_entry โ€” finds an entry in passwd with the given user id.

Raises Not_found if no such entry exists, or always on Windows.

  • val getgrgid : int -> group_entry โ€” finds an entry in group with the given group id.

Raises Not_found if no such entry exists, or always on Windows.

๐ŸŒ Internet addresses ๐ŸŒ

type inet_addr = Unix.inet_addr

The abstract type of Internet addresses.

  • val inet_addr_of_string : string -> inet_addr โ€” 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.

Oh and also โ€” it raises Failure when you hand it a string that doesn't match those formats. Rude but fair. ๐Ÿ’…

val string_of_inet_addr : inet_addr -> string

Give it an Internet address, get back the printable version. The printable representation is exactly the same one described in UnixLabels.inet_addr_of_string, so it's a two-way street bestie ๐Ÿ”โœจ

val inet_addr_any : inet_addr

A special IPv4 address โ€” and no cap, it's for use only with bind. It means "all the Internet addresses this host machine has." Like, all of them. Every single one. ๐ŸŒ

val inet_addr_loopback : inet_addr

A special IPv4 address representing the host machine, aka 127.0.0.1. The classic. The icon. The "there's no place like home" address ๐Ÿ ๐Ÿ’–

val inet6_addr_any : inet_addr

Same vibe as inet_addr_any but for IPv6 โ€” again, only use it with bind, and it represents all the Internet addresses the host machine possesses โœจ

val inet6_addr_loopback : inet_addr

A special IPv6 address for the host machine itself: ::1. IPv6's little loopback moment ๐Ÿฆ‹

val is_inet6_addr : inet_addr -> bool

Tells you whether the inet_addr you passed is an IPv6 address. Yes/no, simple as ๐ŸŽ€

Since 4.12


๐Ÿงฆ Sockets ๐Ÿงฆ

type socket_domain = Unix.socket_domain =
  | PF_UNIX   (* Unix domain *)
  | PF_INET   (* Internet domain (IPv4) *)
  | PF_INET6  (* Internet domain (IPv6) *)

This is the type of socket domains, bestie. Heads up though: not all platforms support IPv6 sockets (that's the PF_INET6 one), so don't come crying to me when it's not there ๐Ÿ˜ญ

On Windows: PF_UNIX is supported since 4.14.0 on Windows 10 1803 and later. Windows girlies stay winning (eventually) ๐ŸชŸ

type socket_type = Unix.socket_type =
  | SOCK_STREAM     (* Stream socket *)
  | SOCK_DGRAM      (* Datagram socket *)
  | SOCK_RAW        (* Raw socket *)
  | SOCK_SEQPACKET  (* Sequenced packets socket *)

The type of socket kinds โ€” it specifies the semantics of the communications. And SOCK_SEQPACKET? It's included for completeness only, lowkey. It's rarely supported by the OS, and it needs system calls that are not available in this library. So like... it's there, but don't get attached ๐Ÿ’€

type sockaddr = Unix.sockaddr =
  | ADDR_UNIX of string
  | ADDR_INET of inet_addr * int

The type of socket addresses, periodt.

  • ADDR_UNIX name โ€” a socket address in the Unix domain; name is a file name in the file system.
  • ADDR_INET(addr,port) โ€” a socket address in the Internet domain; addr is the Internet address of the machine, and port is the port number.
val socket : ?cloexec:bool -> domain:socket_domain -> kind:socket_type
             -> protocol:int -> file_descr

Creates a new socket in the domain you give it, with the kind you give it. The third argument is the protocol type; 0 selects the default protocol for that kind of socket. And for the cloexec optional argument, go read UnixLabels.set_close_on_exec โ€” it's all documented there, iykyk ๐Ÿซถ

val domain_of_sockaddr : sockaddr -> socket_domain

Hands you back the socket domain that's adequate for the given socket address. Matching game fr ๐ŸŽฏ

val socketpair : ?cloexec:bool -> domain:socket_domain ->
                 kind:socket_type -> protocol:int -> file_descr * file_descr

Creates a pair of unnamed sockets, connected together. Two little guys, holding hands ๐Ÿซฑ๐Ÿซฒ Again, cloexec documentation lives at UnixLabels.set_close_on_exec.

val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr

Accepts connections on the given socket. The descriptor it returns is a socket connected to the client; the returned address is the address of that connecting client. Very "you're in, come on in" energy ๐Ÿ‘‘ Same deal, cloexec docs at UnixLabels.set_close_on_exec.

val bind : file_descr -> addr:sockaddr -> unit

Binds a socket to an address. Sprinkle a little commitment on it โœจ

val connect : file_descr -> addr:sockaddr -> unit

Connects a socket to an address. Slay.

val listen : file_descr -> max:int -> unit

Sets up a socket for receiving connection requests. That integer argument? It's the maximal number of pending requests. So like, the queue length before things start getting awkward ๐Ÿ’…

type shutdown_command = Unix.shutdown_command =
  | SHUTDOWN_RECEIVE  (* Close for receiving *)
  | SHUTDOWN_SEND     (* Close for sending *)
  | SHUTDOWN_ALL      (* Close both *)

The type of commands for shutdown. All killer, no filler.

val shutdown : file_descr -> mode:shutdown_command -> unit

Shuts down a socket connection. Careful with which mode, bestie:

  • SHUTDOWN_SEND as the 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 (the SIGPIPE signal). โš ๏ธ
val getsockname : file_descr -> sockaddr

Returns the address of the given socket. Hi, who are you ๐Ÿ“

val getpeername : file_descr -> sockaddr

Returns the address of the host connected to the given socket. Hi, who are you ๐Ÿ‘€

type msg_flag = Unix.msg_flag =
  | MSG_OOB
  | MSG_DONTROUTE
  | MSG_PEEK

The flags for UnixLabels.recv, UnixLabels.recvfrom, UnixLabels.send and UnixLabels.sendto. The little modifiers of the message world ๐ŸŽ€

val recv : file_descr -> buf:bytes -> pos:int -> len:int ->
           mode:msg_flag list -> int

Receive data from a connected socket. Data incoming, bestie ๐Ÿ“ฅ

val recvfrom : file_descr -> buf:bytes -> pos:int -> len:int ->
               mode:msg_flag list -> int * sockaddr

Receive data from an *un*connected socket โ€” and it also tells you who sent it, which is honestly so helpful of it ๐Ÿซถ

val send : file_descr -> buf:bytes -> pos:int -> len:int ->
           mode:msg_flag list -> int

Send data over a connected socket. Out it goes ๐Ÿ“ค

val send_substring : file_descr -> buf:string -> pos:int -> len:int ->
                     mode:msg_flag list -> int

Same as send, but it takes the data from a string instead of a byte sequence. String girlies rise ๐Ÿงš

Since 4.02

val sendto : file_descr -> buf:bytes -> pos:int -> len:int ->
             mode:msg_flag list -> addr:sockaddr -> int

Send data over an unconnected socket. You gotta say where to, hence the addr.

val sendto_substring : file_descr -> buf:string -> pos:int -> len:int ->
                       mode:msg_flag list -> sockaddr -> int

Same as sendto, but the data comes from a string instead of a byte sequence ๐Ÿ’œ

Since 4.02


๐ŸŒธ Socket options ๐ŸŒธ

type socket_bool_option = Unix.socket_bool_option =
  | SO_DEBUG        (* Record debugging information *)
  | SO_BROADCAST    (* Permit sending of broadcast messages *)
  | SO_REUSEADDR    (* Allow reuse of local addresses for bind *)
  | SO_KEEPALIVE    (* Keep connection active *)
  | SO_DONTROUTE    (* Bypass the standard routing algorithms *)
  | SO_OOBINLINE    (* Leave out-of-band data in line *)
  | SO_ACCEPTCONN   (* Report whether socket listening is enabled *)
  | TCP_NODELAY     (* Control the Nagle algorithm for TCP sockets *)
  | IPV6_ONLY       (* Forbid binding an IPv6 socket to an IPv4 address *)
  | SO_REUSEPORT    (* Allow reuse of address and port bindings.

                       Since 4.12.
                     *)

These are the socket options you can consult with UnixLabels.getsockopt and modify with UnixLabels.setsockopt. They've got a boolean (true / false) value โ€” it's giving on/off switch ๐Ÿ”˜

type socket_int_option = Unix.socket_int_option =
  | SO_SNDBUF     (* Size of send buffer *)
  | SO_RCVBUF     (* Size of received buffer *)
  | SO_ERROR      (* Deprecated. Use UnixLabels.getsockopt_error instead. *)
  | SO_TYPE       (* Report the socket type *)
  | SO_RCVLOWAT   (* Minimum number of bytes to process for input
                     operations *)
  | SO_SNDLOWAT   (* Minimum number of bytes to process for output
                     operations *)

These get consulted with UnixLabels.getsockopt_int and modified with UnixLabels.setsockopt_int. They have an integer value ๐Ÿ”ข

โš ๏ธ Real talk: SO_ERROR is deprecated. Use UnixLabels.getsockopt_error instead. Don't be that girl using the deprecated option ๐Ÿ˜ญ
type socket_optint_option = Unix.socket_optint_option =
  | SO_LINGER  (* Whether to linger on closed connections that have data
                  present, and for how long (in seconds) *)

Consulted with UnixLabels.getsockopt_optint, modified with UnixLabels.setsockopt_optint. Its value is of type int option, where None means "disabled". The option of options, truly ๐Ÿ’…

type socket_float_option = Unix.socket_float_option =
  | SO_RCVTIMEO  (* Timeout for input operations *)
  | SO_SNDTIMEO  (* Timeout for output operations *)

Consulted with UnixLabels.getsockopt_float, modified with UnixLabels.setsockopt_float. These have a floating-point value representing a time in seconds. And the value 0 means infinite timeout โ€” no clock, no stress, no cap โณโœจ

val getsockopt : file_descr -> socket_bool_option -> bool

Returns the current status of a boolean-valued option in the given socket. Spill the tea, socket โ˜•

val setsockopt : file_descr -> socket_bool_option -> bool -> unit

Sets or clears a boolean-valued option in the given socket. Setting and clearing, both iconic ๐ŸŽ€

val getsockopt_int : file_descr -> socket_int_option -> int

Same as UnixLabels.getsockopt, but for an integer-valued socket option.

val setsockopt_int : file_descr -> socket_int_option -> int -> unit

Same as UnixLabels.setsockopt, but for an integer-valued socket option.

val getsockopt_optint : file_descr -> socket_optint_option -> int option

Same as UnixLabels.getsockopt, but for a socket option whose value is an int option.

val setsockopt_optint : file_descr -> socket_optint_option -> int option
                        -> unit

Same as UnixLabels.setsockopt, but for a socket option whose value is an int option.

val getsockopt_float : file_descr -> socket_float_option -> float

Same as UnixLabels.getsockopt, but for a socket option whose value is a floating-point number.

val setsockopt_float : file_descr -> socket_float_option -> float -> unit

Same as UnixLabels.setsockopt, but for a socket option whose value is a floating-point number.

val getsockopt_error : file_descr -> error option

Returns the error condition associated with the given socket โ€” and clears it. Like, it tells you what went wrong and wipes the board clean. Main character behaviour, honestly ๐Ÿ‘‘


๐Ÿฆ‹ High-level network connection functions ๐Ÿฆ‹

val open_connection : sockaddr -> in_channel * out_channel

Connects to a server at the given address and returns a pair of buffered channels connected to that server. Big reminder though: remember to call flush on the output channel at the right times to make sure everything stays correctly synchronized ๐Ÿ˜ค

Also important, bestie โ€” the two channels returned by open_connection share a descriptor to a socket. So when the connection is over, you should call close_out on the output channel, which will also close the underlying socket. And do not call close_in on the input channel โ€” it'll get collected by the GC eventually. Let the garbage collector handle it, it's literally its job ๐Ÿ™ˆ

val shutdown_connection : in_channel -> unit

"Shuts down" a connection established with UnixLabels.open_connection โ€” that is, it transmits an end-of-file condition to the server reading on the other side of the connection. Important: this does not close the socket, and it does not close the channels used by the connection. For how to close them once the connection is actually over, see Unix.open_connection ๐Ÿ“–

val establish_server : (in_channel -> out_channel -> unit) ->
                       addr:sockaddr -> unit

Establishes a server on the given address. The function you pass as the first argument gets called for each connection, with two buffered channels connected to the client. A new process is created for each connection. And heads up: the function UnixLabels.establish_server never returns normally. It's in it for life, no cap ๐Ÿ’€๐Ÿ‘‘

okay so about those two channels the function gives you? They literally share a descriptor to a socket ๐Ÿ’…. You do not need to close the channels, because that happens automatically when the function returns โœจ. If you're the kind of bestie who prefers explicit closing, close the output channel using close_out and leave the input channel unclosed โ€” the reasons are explained in Unix.in_channel_of_descr ๐Ÿซถ.

๐Ÿ’€ Windows heads up: this raises Invalid_argument. Use threads instead.

๐ŸŒธ Host and protocol databases ๐ŸŒธ

๐ŸŽ€ type host_entry

type host_entry = Unix.host_entry = {
        h_name : string ;
        h_aliases : string array ;
        h_addrtype : socket_domain ;
        h_addr_list : inet_addr array ;
        }

This is the structure of entries in the hosts database, bestie ๐Ÿฆ‹.

๐ŸŽ€ type protocol_entry

type protocol_entry = Unix.protocol_entry = {
        p_name : string ;
        p_aliases : string array ;
        p_proto : int ;
        }

This is the structure of entries in the protocols database โœจ.

๐ŸŽ€ type service_entry

type service_entry = Unix.service_entry = {
        s_name : string ;
        s_aliases : string array ;
        s_port : int ;
        s_proto : string ;
        }

This is the structure of entries in the services database ๐Ÿซถ.

๐ŸŒŸ val gethostname : unit -> string

Returns the name of the local host. iconic behavior, no notes ๐Ÿ’–.

๐ŸŒŸ val gethostbyname : string -> host_entry

Finds an entry in hosts with the given name ๐Ÿ”.

Raises Not_found if no such entry exists.

๐ŸŒŸ val gethostbyaddr : inet_addr -> host_entry

Finds an entry in hosts with the given address ๐Ÿ”.

Raises Not_found if no such entry exists.

๐ŸŒŸ val getprotobyname : string -> protocol_entry

Finds an entry in protocols with the given name ๐Ÿ”.

Raises Not_found if no such entry exists.

๐ŸŒŸ val getprotobynumber : int -> protocol_entry

Finds an entry in protocols with the given protocol number ๐Ÿ”.

Raises Not_found if no such entry exists.

๐ŸŒŸ val getservbyname : string -> protocol:string -> service_entry

Finds an entry in services with the given name ๐Ÿ”.

Raises Not_found if no such entry exists.

๐ŸŒŸ val getservbyport : int -> protocol:string -> service_entry

Finds an entry in services with the given service number ๐Ÿ”.

Raises Not_found if no such entry exists.

๐Ÿฆ‹ type addr_info

type addr_info = Unix.addr_info = {
        ai_family : socket_domain ;  (* Socket domain
        *)
        ai_socktype : socket_type ;  (* Socket type
        *)
        ai_protocol : int ;  (* Socket protocol number
        *)
        ai_addr : sockaddr ;  (* Address
        *)
        ai_canonname : string ;  (* Canonical host name
        *)
        }

Address information returned by UnixLabels.getaddrinfo โœจ.

๐Ÿฆ‹ type getaddrinfo_option

type getaddrinfo_option = Unix.getaddrinfo_option =
        | AI_FAMILY of socket_domain
         (* Impose the given socket domain
        *)
        | AI_SOCKTYPE of socket_type
         (* Impose the given socket type
        *)
        | AI_PROTOCOL of int
         (* Impose the given protocol
        *)
        | AI_NUMERICHOST  (* Do not call name resolver, expect numeric IP
       address
        *)
        | AI_CANONNAME  (* Fill the ai_canonname field of the result
        *)
        | AI_PASSIVE  (* Set address to ``any'' address for use with
       UnixLabels.bind

        *)

Options to UnixLabels.getaddrinfo ๐ŸŽ€.

๐ŸŒˆ val getaddrinfo : string -> string -> getaddrinfo_option list -> addr_info list

getaddrinfo host service opts returns a list of UnixLabels.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 if the constraints expressed in opts cannot be satisfied. no cap.

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 on 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 lets the caller force a particular socket domain (e.g. IPv6 only or IPv4 only) or a particular socket type (e.g. TCP only or UDP only) ๐Ÿ’….

๐Ÿฆ‹ type name_info

type name_info = Unix.name_info = {
        ni_hostname : string ;  (* Name or IP address of host
        *)
        ni_service : string ;  (* Name of service or port number
        *)
        }

Host and service information returned by UnixLabels.getnameinfo โœจ.

๐Ÿฆ‹ type getnameinfo_option

type getnameinfo_option = Unix.getnameinfo_option =
        | NI_NOFQDN  (* Do not qualify local host names
        *)
        | NI_NUMERICHOST  (* Always return host as IP address
        *)
        | NI_NAMEREQD  (* Fail if host name cannot be determined
        *)
        | NI_NUMERICSERV  (* Always return service as port number
        *)
        | NI_DGRAM  (* Consider the service as UDP-based instead of the default
       TCP
        *)

Options to UnixLabels.getnameinfo ๐ŸŽ€.

๐ŸŒˆ val getnameinfo : sockaddr -> getnameinfo_option list -> name_info

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.

Raises Not_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, bestie ๐Ÿซถ.

๐ŸŽ€ type terminal_io

type terminal_io = Unix.terminal_io = {

        mutable c_ignbrk : bool ;  (* Ignore the break condition.
         *)

        mutable c_brkint : bool ;  (* Signal interrupt on break condition.
         *)

        mutable c_ignpar : bool ;  (* Ignore characters with parity errors.
         *)

        mutable c_parmrk : bool ;  (* Mark parity errors.
         *)

        mutable c_inpck : bool ;  (* Enable parity check on input.
         *)

        mutable c_istrip : bool ;  (* Strip 8th bit on input characters.
         *)

        mutable c_inlcr : bool ;  (* Map NL to CR on input.
         *)

        mutable c_igncr : bool ;  (* Ignore CR on input.
         *)

        mutable c_icrnl : bool ;  (* Map CR to NL on input.
         *)

        mutable c_ixon : bool ;  (* Recognize XON/XOFF characters on input.
         *)

        mutable c_ixoff : bool ;  (* Emit XON/XOFF chars to control input flow.
         *)

        mutable c_opost : bool ;  (* Enable output processing.
         *)

        mutable c_obaud : int ;  (* Output baud rate (0 means close connection).
         *)

        mutable c_ibaud : int ;  (* Input baud rate.
         *)

        mutable c_csize : int ;  (* Number of bits per character (5-8).
         *)

        mutable c_cstopb : int ;  (* Number of stop bits (1-2).
         *)

        mutable c_cread : bool ;  (* Reception is enabled.
         *)

        mutable c_parenb : bool ;  (* Enable parity generation and detection.
         *)

        mutable c_parodd : bool ;  (* Specify odd parity instead of even.
         *)

        mutable c_hupcl : bool ;  (* Hang up on last close.
         *)

        mutable c_clocal : bool ;  (* Ignore modem status lines.
         *)

        mutable c_isig : bool ;  (* Generate signal on INTR, QUIT, SUSP.
         *)

        mutable c_icanon : bool ;  (* Enable canonical processing (line
       buffering and editing)
         *)

        mutable c_noflsh : bool ;  (* Disable flush after INTR, QUIT, SUSP.
         *)

        mutable c_echo : bool ;  (* Echo input characters.
         *)

        mutable c_echoe : bool ;  (* Echo ERASE (to erase previous character).
         *)

        mutable c_echok : bool ;  (* Echo KILL (to erase the current line).
         *)

        mutable c_echonl : bool ;  (* Echo NL even if c_echo is not set.
         *)

        mutable c_vintr : char ;  (* Interrupt character (usually ctrl-C).
         *)

        mutable c_vquit : char ;  (* Quit character (usually ctrl-\).
         *)

        mutable c_verase : char ;  (* Erase character (usually DEL or ctrl-H).
         *)

        mutable c_vkill : char ;  (* Kill line character (usually ctrl-U).
         *)

        mutable c_veof : char ;  (* End-of-file character (usually ctrl-D).
         *)

        mutable c_veol : char ;  (* Alternate end-of-line char. (usually none).
         *)

        mutable c_vmin : int ;  (* Minimum number of characters to read before
       the read request is satisfied.
         *)

        mutable c_vtime : int ;  (* Maximum read wait (in 0.1s units).
         *)

        mutable c_vstart : char ;  (* Start character (usually ctrl-Q).
         *)

        mutable c_vstop : char ;  (* Stop character (usually ctrl-S).
         *)
        }

๐ŸŒŸ val tcgetattr : file_descr -> terminal_io

Returns the status of the terminal referred to by the given file descriptor ๐Ÿ–ฅ๏ธ.

Raises Invalid_argument on Windows.

๐ŸŒŸ type setattr_when

type setattr_when = Unix.setattr_when =
        | TCSANOW
        | TCSADRAIN
        | TCSAFLUSH

๐ŸŒŸ val tcsetattr : file_descr -> mode:setattr_when -> terminal_io -> unit

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

Raises Invalid_argument on Windows.

๐ŸŒŸ val tcsendbreak : file_descr -> duration:int -> unit

Sends 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).

Raises Invalid_argument on Windows.

๐ŸŒŸ val tcdrain : file_descr -> unit

Waits until all output written on the given file descriptor has been transmitted ๐Ÿซถ.

Raises Invalid_argument on Windows.

๐ŸŒŸ type flush_queue

type flush_queue = Unix.flush_queue =
        | TCIFLUSH
        | TCOFLUSH
        | TCIOFLUSH

๐ŸŒŸ val tcflush : file_descr -> mode:flush_queue -> unit

Discards 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 ๐Ÿงนโœจ.

Raises Invalid_argument on Windows.

๐ŸŒŸ type flow_action

type flow_action = Unix.flow_action =
        | TCOOFF
        | TCOON
        | TCIOFF
        | TCION

๐ŸŒŸ val tcflow : file_descr -> mode:flow_action -> unit

Suspends or restarts 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 ๐Ÿšฆ.

Raises Invalid_argument on Windows.

๐ŸŒŸ val setsid : unit -> int

Puts the calling process in a new session and detaches it from its controlling terminal ๐Ÿ‘‘.

Raises Invalid_argument on Windows.


and that's the whole vibe, bestie ๐Ÿซถโœจ โ€” this iconic page was brought to you by OCamldoc, dated 2026-06-22, for UnixLabels(3). periodt ๐Ÿ’…

๐Ÿ“ฆ where this page comes from
  • arch rolling: ocaml 5.5.0-1 ยท LGPL2.1 AND custom: QPL-1.0
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms