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 theUnixLabels.Unix_errorexception whenever the underlying system call signals an error. The only two exceptions to that rule areUnixLabels.error_messageandUnixLabels.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 unavailableECHILDโ no child processEDEADLKโ resource deadlock would occur ๐ตEDOMโ domain error for math functions, etc. ๐งฎEEXISTโ file existsEFAULTโ bad addressEFBIGโ file too large ๐EINTRโ function interrupted by signal โกEINVALโ invalid argumentEIOโ hardware I/O error ๐EISDIRโ is a directory ๐EMFILEโ too many open files by the processEMLINKโ too many linksENAMETOOLONGโ filename too long ๐ENFILEโ too many open files in the systemENODEVโ no such deviceENOENTโ no such file or directory ๐ENOEXECโ not an executable fileENOLCKโ no locks available ๐ENOMEMโ not enough memory ๐ญENOSPCโ no space left on deviceENOSYSโ function not supportedENOTDIRโ not a directoryENOTEMPTYโ directory not emptyENOTTYโ inappropriate I/O control operationENXIOโ no such device or addressEPERMโ operation not permitted ๐EPIPEโ broken pipe ๐ERANGEโ result too largeEROFSโ read-only file systemESPIPEโ invalid seek e.g. on a pipeESRCHโ no such processEXDEVโ invalid linkEWOULDBLOCKโ operation would blockEINPROGRESSโ operation now in progress โณEALREADYโ operation already in progressENOTSOCKโ socket operation on non-socket ๐งฆEDESTADDRREQโ destination address requiredEMSGSIZEโ message too longEPROTOTYPEโ protocol wrong type for socketENOPROTOOPTโ protocol not availableEPROTONOSUPPORTโ protocol not supportedESOCKTNOSUPPORTโ socket type not supportedEOPNOTSUPPโ operation not supported on socketEPFNOSUPPORTโ protocol family not supportedEAFNOSUPPORTโ address family not supported by protocol familyEADDRINUSEโ address already in use ๐ฎEADDRNOTAVAILโ can't assign requested addressENETDOWNโ network is down ๐กENETUNREACHโ network is unreachableENETRESETโ network dropped connection on resetECONNABORTEDโ software caused connection abortECONNRESETโ connection reset by peer ๐ENOBUFSโ no buffer space availableEISCONNโ socket is already connectedENOTCONNโ socket is not connectedESHUTDOWNโ can't send after socket shutdownETOOMANYREFSโ too many references: can't spliceETIMEDOUTโ connection timed out โECONNREFUSEDโ connection refused ๐EHOSTDOWNโ host is downEHOSTUNREACHโ no route to hostELOOPโ too many levels of symbolic links ๐EOVERFLOWโ file size or position not representableEUNKNOWNERR 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_errorandUnix.Unix_errorare 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โ sohandle_unix_error f xappliesftoxand returns the result. But if the exceptionUnixLabels.Unix_errorgets raised, it prints a message describing the error and then exits with code2. Iconic behaviour ngl ๐
๐ฆ Access to the process environment ๐ฆ
val environment : unit -> string arrayโ returns the process environment as an array of strings formatted likevariable=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 formattedvariable=value, but unlikeUnixLabels.environment, this one returns a populated array even if the process has special privileges ๐ณ See the documentation forUnixLabels.unsafe_getenvfor more details. Since 4.12val getenv : string -> stringโ returns the value associated to a variable in the process environment, unless the process has special privileges. RaisesNot_foundif the variable is unbound or the process has special privileges. Also it's identical toSys.getenv๐val unsafe_getenv : string -> stringโ returns the value associated to a variable in the process environment. UnlikeUnixLabels.getenv, this one returns the value even if the process has special privileges. And why's it called unsafe? Because the programmer of asetuidorsetgidprogram 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. RaisesNot_foundif the variable is unbound.val putenv : string -> string -> unitโputenv name valuesets the value associated to a variable in the process environment.nameis the name of the environment variable, andvalueis its new associated value ๐val unsetenv : string -> unitโunsetenv nameremoves the variablenamefrom 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 byexit; 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: onlyWEXITEDis 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, theSTATUS_ACCESS_VIOLATIONerror code is the 32-bit0xC0000005: asInt32.of_int 0xC0000005is-1073741819,WEXITED -1073741819is the Windows equivalent ofWSIGNALED Sys.sigsegv. Like, that's the whole mapping, bestie ๐ง
type wait_flag = Unix.wait_flag =โ flags forUnixLabels.waitpid:WNOHANGโ do not block if no child has died yet, but immediately return with a pid equal to0๐โโ๏ธWUNTRACEDโ report also the children that receive stop signals โ
val execv : prog:string -> args:string array -> 'aโexecv prog argsexecutes the program in fileprog, with the argumentsargs, and the current process environment. Quick note: the first argument,args.(0), is by convention the filename of the program being executed, just likeSys.argv.(0)๐ And theseexecv*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. UsingUnixLabels.create_processor one of theopen_process_*functions instead is recommended ๐
Raises Unix_error on failure.
val execve : prog:string -> args:string array -> env:string array -> 'aโ same asUnixLabels.execv, except that the third argument provides the environment to the program executed ๐val execvp : prog:string -> args:string array -> 'aโ same asUnixLabels.execv, except that the program is searched in thepath๐val execvpe : prog:string -> args:string array -> env:string array -> 'aโ same asUnixLabels.execve, except that the program is searched in thepath๐val fork : unit -> intโ forks a new process, classic. The returned integer is0for 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 theThreadmodule has been spawned, then the child process might be in a corrupted state ๐ญ so be careful. RaisesInvalid_argumenton Windows โ useUnixLabels.create_processor threads instead. RaisesFailureif 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 โณ RaisesInvalid_argumenton Windows โ useUnixLabels.waitpidinstead.val waitpid : mode:wait_flag list -> int -> int * process_statusโ same asUnixLabels.wait, but it waits for the child process whose pid is given ๐ฏ A pid of-1means wait for any child. A pid of0means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whetherwaitpidshould 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: usually0for "no errors" and a small positive integer for "yeah that failed".
๐จ Unlikeexit,Unix._exitperforms no finalization whatsoever โ functions registered withat_exitare 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 thenice'' value. (Highernice'' 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 readingO_WRONLYโ Open for writingO_RDWRโ Open for reading and writingO_NONBLOCKโ Open in non-blocking modeO_APPENDโ Open for appendO_CREATโ Create if nonexistentO_TRUNCโ Truncate to 0 length if existingO_EXCLโ Fail if existingO_NOCTTYโ Don't make this dev a controlling ttyO_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 onO_SYNC/O_DSYNC)O_SHARE_DELETEโ Windows only: allow the file to be deleted while still openO_CLOEXECโ Set the close-on-exec flag on the descriptor returned byUnixLabels.openfile. SeeUnixLabels.set_close_on_execfor 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 (seeUnixLabels.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 ~lenreadslenbytes from descriptorfd, stores them in byte sequencebuf, starting at positionposinbuf. 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 asUnixLabels.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 ~lenwriteslenbytes to descriptorfd, taking them from byte sequencebuf, starting at positionposinbuf. Returns the number of bytes actually written. Important:writerepeats 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 asUnixLabels.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 asUnixLabels.write, but it attempts to write only once. So if an error occurs,single_writeguarantees that no data has been written. Iconic all-or-nothing behaviour. ๐ฅval write_substring : file_descr -> buf:string -> pos:int -> len:int -> intโ Same asUnixLabels.write, but takes the data from astringinstead of a byte sequence.
Since 4.02
val single_write_substring : file_descr -> buf:string -> pos:int -> len:int -> intโ Same asUnixLabels.single_write, but takes the data from astringinstead 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 asUnixLabels.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 fileSEEK_CURโ indicates positions relative to the current positionSEEK_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 fileS_DIRโ DirectoryS_CHRโ Character deviceS_BLKโ Block deviceS_LNKโ Symbolic linkS_FIFOโ Named pipeS_SOCKโ Socket
type stats = Unix.stats = {
st_dev : intโ Device numberst_ino : intโ Inode numberst_kind : file_kindโ Kind of the filest_perm : file_permโ Access rightsst_nlink : intโ Number of linksst_uid : intโ User id of the ownerst_gid : intโ Group ID of the file's groupst_rdev : intโ Device ID (if special file)st_size : intโ Size in bytesst_atime : floatโ Last access timest_mtime : floatโ Last modification timest_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 asUnixLabels.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โ Returnstrueif the given file descriptor refers to a terminal or console window,falseotherwise.
๐ฆ 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:
EPERMon POSIX compliant systemEISDIRon Linux >= 2.1.132EACCESSon Windows
val rename : src:string -> dst:string -> unitโrename ~src ~dstchanges the name of a file fromsrctodst, moving it between directories if needed. Ifdstalready exists, its contents will be replaced with those ofsrc. Depending on the operating system, the metadata (permissions, owner, etc) ofdstcan either be preserved or be replaced by those ofsrc.val link : ?follow:bool -> src:string -> dst:string -> unitโlink ?follow ~src ~dstcreates a hard link nameddstto the file namedsrc.
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 pis an absolute pathname forpobtained 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_argumenton Windows.
- Raises
val chown : string -> uid:int -> gid:int -> unitโ change the owneruidand ownergidof the named file.- Raises
Invalid_argumenton Windows.
- Raises
val fchown : file_descr -> uid:int -> gid:int -> unitโ change the owneruidand ownergidof an opened file.- Raises
Invalid_argumenton Windows.
- Raises
val umask : file_perm -> file_permโ set the process's file mode creation mask, and return the previous mask.- Raises
Invalid_argumenton Windows.
- Raises
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. SeeUnixLabels.set_close_on_execfor documentation on thecloexecoptional argument.val dup2 : ?cloexec:bool -> src:file_descr -> dst:file_descr -> unitโdup2 ~src ~dstduplicatessrctodst, closingdstif already opened. SeeUnixLabels.set_close_on_execfor documentation on thecloexecoptional argument.val set_nonblock : file_descr -> unitโ set thenon-blockingflag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises theEAGAINorEWOULDBLOCKerror instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raisesEAGAINorEWOULDBLOCK.val clear_nonblock : file_descr -> unitโ clear thenon-blockingflag on the given descriptor. SeeUnixLabels.set_nonblock.val set_close_on_exec : file_descr -> unitโ set theclose-on-execflag 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 theexec,create_processandopen_processfunctions.
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 theclose-on-execflag on the given descriptor. SeeUnixLabels.set_close_on_exec.
๐ Directories
val mkdir : string -> perm:file_perm -> unitโ create a directory with the given permissions (seeUnixLabels.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_argumenton Windows.
- Raises
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_filewhen the end of the directory has been reached.
- Raises
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. SeeUnixLabels.set_close_on_execfor documentation on thecloexecoptional argument.val mkfifo : string -> perm:file_perm -> unitโ create a named pipe with the given permissions (seeUnixLabels.umask).- Raises
Invalid_argumenton Windows.
- Raises
๐๏ธ 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.
๐ Symbolic links ๐
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 functionsSys.signalandSys.set_signal.
val kill : pid:int -> signal:Sys.signal -> unitโkill ~pid ~signalsends signal numbersignalto the process with idpid.
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 sigschanges the set of blocked signals. IfmodeisSIG_SETMASK, blocked signals are set to those in the listsigs. IfmodeisSIG_BLOCK, the signals insigsare added to the set of blocked signals. IfmodeisSIG_UNBLOCK, the signals insigsare removed from the set of blocked signals.sigprocmaskreturns 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 sigsatomically sets the blocked signals tosigsand 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 sigswaits until one of the signals in the listsigsbecomes 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 insigswill not be invoked. The signalssigsare expected to be blocked before callingsigwait.
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 asUnixLabels.time, but with resolution better than 1 second.val gmtime : float -> tmโ converts a time in seconds, as returned byUnixLabels.time, into a date and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. To perform the inverse conversion, set theTZenvironment variable to"UTC", useUnixLabels.mktime, and then restore the original value ofTZ.val localtime : float -> tmโ converts a time in seconds, as returned byUnixLabels.time, into a date and a time. Assumes the local time zone. The function performing the inverse conversion isUnixLabels.mktime.val mktime : tm -> float * tmโ converts a date and time, specified by thetmargument, into a time in seconds, as returned byUnixLabels.time. Thetm_isdst,tm_wdayandtm_ydayfields oftmare ignored. Also returns a normalized copy of the giventmrecord, with thetm_wday,tm_yday, andtm_isdstfields recomputed from the other fields, and the other fields normalized (so that, e.g., 40 October is changed into 9 November). Thetmargument is interpreted in the local time zone.val alarm : int -> intโ schedules aSIGALRMsignal 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. Likesleep, 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 are0.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 ssets the interval timertand returns its previous status. Thesargument 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 reloadingit_valuewhen the timer expires. Settings.it_valueto zero disables the timer. Settings.it_intervalto 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 groupssets the supplementary group IDs for the calling process. Appropriate privileges are required.
Raises Invalid_argument on Windows.
val initgroups : string -> int -> unitโinitgroups user groupinitializes the group access list by reading the group database/etc/groupand using all groups of whichuseris a member. The additional groupgroupis 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;nameis a file name in the file system.ADDR_INET(addr,port)โ a socket address in the Internet domain;addris the Internet address of the machine, andportis 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_SENDas the second argument causes reads on the other end of the connection to return an end-of-file condition.SHUTDOWN_RECEIVEcauses writes on the other end of the connection to return a closed pipe condition (theSIGPIPEsignal). โ ๏ธ
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_ERRORis deprecated. UseUnixLabels.getsockopt_errorinstead. 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