Module Lwt_unix
Contents
Instructions: Use this module in your project
In the IDE (CLion, Visual Studio Code, Xcode, etc.) you use for your DkSDK project:
Add the following to your project's
dependencies/CMakeLists.txt:DkSDKProject_DeclareAvailable(lwt CONSTRAINT "= " FINDLIBS lwt lwt.unix) DkSDKProject_MakeAvailable(lwt)Add the
Findlib::lwtlibrary to any desired targets insrc/*/CMakeLists.txt:target_link_libraries(YourPackage_YourLibraryName # ... existing libraries, if any ... Findlib::lwt)Click your IDE's
Buildbutton
Not using DkSDK?
FIRST, do one or all of the following:
Run:
opam install lwt.nullEdit your
dune-projectand add:(package (name YourExistingPackage) (depends ; ... existing dependenices ... (lwt (>= ))))Then run:
dune build *.opam # if this fails, run: dune buildEdit your
<package>.opamfile and add:depends: [ # ... existing dependencies ... "lwt" {>= ""} ]Then run:
opam install . --deps-only
FINALLY, add the lwt.unix library to any desired (library)and/or (executable) targets in your **/dune files:
(library
(name YourLibrary)
; ... existing library options ...
(libraries
; ... existing libraries ...
lwt.unix))
(executable
(name YourExecutable)
; ... existing executable options ...
(libraries
; ... existing libraries ...
lwt.unix))This modules maps system calls, like those of the standard library's
Unix module, to cooperative ones, which will not
block the program.
The semantics of all operations is the following: if the action (for example reading from a file descriptor) can be performed immediately, it is performed and returns an already resolved promise, otherwise it returns a pending promise which is resolved when the operation completes.
Most operations on sockets and pipes (on Windows it is only sockets) are
cancelable, meaning you can cancel them with
Lwt.cancel. For example if you want to read
something from a file descriptor with a timeout, you can cancel the
action after the timeout and the reading will not be performed if not
already done.
For example, consider that you have two sockets sock1 and sock2. You
want to read something from sock1 or exclusively from sock2 and fail
with an exception if a timeout of 1 second expires, without reading
anything from sock1 and sock2, even if they become readable in the
future.
Then you can do:
Lwt.pick
[Lwt_unix.timeout 1.0;
read sock1 buf1 ofs1 len1;
read sock2 buf2 ofs2 len2]In this case, it is guaranteed that exactly one of the three operations will complete, and the others will be cancelled.
Same as
Unix.handle_unix_error but
catches lwt-level exceptions
Sleeping
valsleep : ``float->``unitLwt.t
sleep d is a promise that remains in a pending state for d seconds
after which it is resolved with value ().
valyield : ``unit->``unitLwt.t
yield () is a promise in a pending state. It resumes itself as soon as
possible and resolves with value ().
-
deprecated
Since 5.5.0
yieldis deprecated. Use the more generalLwt.pauseinstead. SeeLwt_main.yieldfor additional details.
valauto_yield : ``float->``unit->``unitLwt.t
-
deprecated
Since 5.5.0. Use
auto_pauseinstead.
valauto_pause : ``float->``unit->``unitLwt.t
auto_pause timeout returns a function f, and f () has the
following behavior:
- If it has been more than
timeoutseconds since the last timef ()behaved likeLwt.pause,f ()callsLwt.pause. - Otherwise, if it has been less than
timeoutseconds,f ()behaves likeLwt.return_unit, i.e. it does not yield.
exceptionTimeout
Exception raised by timeout operations
valtimeout : ``float->'aLwt.t
with_timeout d f is a short-hand for:
Lwt.pick [Lwt_unix.timeout d; f ()]-
raises Timeout
The promise
with_timeout d fraisesTimeoutif the promise returned byf ()takes more thandseconds to resolve.
Operations on file-descriptors
typefile_descr
The abstract type for file descriptors. A Lwt file descriptor is
a pair of a unix file descriptor (of type
Unix.file_descr) and a
state.
A file descriptor may be:
- opened, in which case it is fully usable
- closed or aborted, in which case it is no longer usable
typestate`` =
|Opened(* The file descriptor is opened
*)
|Closed(* The file descriptor has been closed by
close. It must not be used for any operation.*)
|Abortedofexn(* The file descriptor has been aborted, the only operation possible is
close, all others will fail.*)
State of a file descriptor
valstate :file_descr->state
state fd returns the state of fd.
valunix_file_descr :file_descr->Unix.file_descr
Returns the underlying unix file descriptor. It always succeeds,
even if the file descriptor's state is not Opened.
valof_unix_file_descr : ``?blocking:bool->``?set_flags:bool->Unix.file_descr->file_descr
Wraps a Unix file descriptor fd in an Lwt
file_descr fd'.
~blocking controls the internal strategy Lwt uses to perform I/O on
the underlying fd. Regardless of ~blocking, at the API level,
Lwt_unix.read, Lwt_unix.write, etc. on fd' always block the Lwt
promise, but never block the whole process. However, for performance
reasons, it is important that ~blocking match the actual blocking mode
of fd.
If ~blocking is not specified, of_unix_file_descr chooses
non-blocking mode for Unix sockets, Unix pipes, and Windows sockets, and
blocking mode for everything else. Note: not specifying ~blocking
causes fstat to be lazily called on fd, the first time your code
performs I/O on fd'. This fstat call can be expensive, so if you use
of_unix_file_descr a lot, be sure to specify ~blocking explicitly.
of_unix_file_descr runs a system call to set the specified or chosen
blocking mode on the underlying fd.
To prevent of_unix_file_descr from running this system call, you can
pass ~set_flags:false. Note that, in this case, if ~blocking,
whether passed explicitly or chosen by Lwt, does not match the true
blocking mode of the underlying fd, I/O on fd' will suffer
performance degradation.
Note that ~set_flags is effectively always false if running on
Windows and fd is not a socket.
Generally, non-blocking I/O is faster: for blocking I/O, Lwt typically has to run system calls in worker threads to avoid blocking the process. See your system documentation for whether particular kinds of file descriptors support non-blocking I/O.
valblocking :file_descr->``boolLwt.t
blocking fd indicates whether Lwt is internally using blocking or
non-blocking I/O with fd.
Note that this may differ from the blocking mode of the underlying Unix
file descriptor (i.e. unix_file_descr fd).
See of_unix_file_descr for details.
valset_blocking : ``?set_flags:bool->file_descr->``bool->unit
set_blocking fd b causes Lwt to internally use blocking or
non-blocking I/O with fd, according to the value of b.
If ~set_flags is true (the default), Lwt also makes a system call to
set the underlying file descriptor's blocking mode to match. Otherwise,
set_blocking is only informational for Lwt.
It is important that the underlying file descriptor actually have the
same blocking mode as that indicated by b.
See of_unix_file_descr for details.
valabort :file_descr->``exn->unit
abort fd exn makes all current and further uses of the file descriptor
fail with the given exception. This put the file descriptor into the
Aborted state.
If the file descriptor is closed, this does nothing, if it is
aborted, this replace the abort exception by exn.
Note that this only works for reading and writing operations on file descriptors supporting non-blocking mode.
Process handling
valfork : ``unit->int
fork () does the same as Unix.fork.
You must use this function instead of
Unix.fork when you want to use Lwt in
the child process, even if you have not started using Lwt before the
fork.
Notes:
- In the child process all pending
Lwt_unixI/O jobs are abandoned. This may cause the child's copy of their associated promises to remain forever pending. - If you are going to use Lwt in the parent and the child, it is a good
idea to call
Lwt_io.flush_allbefore calllingforkto avoid double-flush. - Otherwise, if you will not use Lwt in the child, call
Lwt_main.Exit_hooks.remove_allto avoid Lwt callingLwt_main.runduring process exit. - None of the above is necessary if you intend to call
exec. Indeed, in that case, it is not even necessary to useLwt_unix.fork. You can useUnix.fork. - To abandon some more promises, see
Lwt_main.abandon_yielded_and_paused.
typeprocess_status`` =Unix.process_status=
|WEXITEDofint
|WSIGNALEDofint
|WSTOPPEDofint
typewait_flag`` =Unix.wait_flag=
|WNOHANG
|WUNTRACED
valwait : ``unit->``(int *process_status)``Lwt.t
Wrapper for Unix.wait
valwaitpid :wait_flaglist``->``int->``(int *process_status)``Lwt.t
A promise-returning analog to
Unix.waitpid. This call is
non-blocking on Unix-like systems, but is always blocking on Windows.
typeresource_usage`` = ``{
ru_utime : float;(* User time used
*)
ru_stime : float;(* System time used
*)
}
Resource usages
valwait4 :wait_flaglist``->``int->``(int *process_status*resource_usage)``Lwt.t
wait4 flags pid returns (pid, status, rusage) where (pid, status)
is the same result as Unix.waitpid flags pid, and rusage contains
accounting information about the child.
On windows it will always returns { utime = 0.0; stime = 0.0 }.
valwait_count : ``unit->int
Returns the number of promises waiting for a child process to terminate.
valsystem : ``string->process_statusLwt.t
Executes the given command, waits until it terminates, and return its
termination status. The string is interpreted by the shell /bin/sh on
Unix and cmd.exe on Windows. The result WEXITED 127 indicates that
the shell couldn't be executed.
Basic file input/output
valstdin :file_descr
The file descriptor for standard input.
valstdout :file_descr
The file descriptor for standard output.
valstderr :file_descr
The file descriptor for standard error.
typefile_perm`` =Unix.file_perm
typeopen_flag`` =Unix.open_flag=
|O_RDONLY
|O_WRONLY
|O_RDWR
|O_NONBLOCK
|O_APPEND
|O_CREAT
|O_TRUNC
|O_EXCL
|O_NOCTTY
|O_DSYNC
|O_SYNC
|O_RSYNC
|O_SHARE_DELETE
|O_CLOEXEC
|O_KEEPEXEC
valopenfile : ``string->open_flaglist``->file_perm->file_descrLwt.t
Wrapper for Unix.openfile.
valclose :file_descr->``unitLwt.t
Close a file descriptor. This close the underlying unix file
descriptor and set its state to Closed.
valread :file_descr->``bytes->``int->``int->``intLwt.t
read fd buf ofs len reads up to len bytes from fd, and writes them
to buf, starting at offset ofs. The function immediately evaluates
to an Lwt promise which waits for the operation to complete. If it
completes successfully, the promise resolves to the number of bytes
actually read, or zero if the end of file has been reached.
Note that the Lwt promise waits for data (or end of file) even if the
underlying file descriptor is in non-blocking mode. See
of_unix_file_descr for a discussion of
non-blocking I/O and Lwt.
If Lwt is using blocking I/O on fd, read writes data into a
temporary buffer, then copies it into buf.
The promise can be rejected with any exception that can be raised by
Unix.read, except
Unix.Unix_error Unix.EAGAIN, Unix.Unix_error Unix.EWOULDBLOCK or
Unix.Unix_error Unix.EINTR.
valpread :file_descr->``bytes->``file_offset:int->``int->``int->``intLwt.t
pread fd buf ~file_offset ofs len on file descriptors allowing seek,
reads up to len bytes from fd at offset file_offset from the
beginning of the file, and writes them to buf, starting at offset
ofs.
On Unix systems, the file descriptor position is unaffected. On Windows it is changed to be just after the last read position.
The promise can be rejected with any exception that can be raised by
read or lseek.
valwrite :file_descr->``bytes->``int->``int->``intLwt.t
write fd buf ofs len writes up to len bytes to fd from buf,
starting at buffer offset ofs. The function immediately evaluates to
an Lwt promise which waits for the operation to complete. If the
operation completes successfully, the promise resolves to the number of
bytes actually written, which may be less than len.
Note that the Lwt promise waits to write even if the underlying file
descriptor is in non-blocking mode. See
of_unix_file_descr for a discussion of
non-blocking I/O and Lwt.
If Lwt is using blocking I/O on fd, buf is copied before writing.
The promise can be rejected with any exception that can be raised by
Unix.single_write, except
Unix.Unix_error Unix.EAGAIN, Unix.Unix_error Unix.EWOULDBLOCK or
Unix.Unix_error Unix.EINTR.
valpwrite :file_descr->``bytes->``file_offset:int->``int->``int->``intLwt.t
pwrite fd buf ~file_offset ofs len on file descriptors allowing seek,
writes up to len bytes to fd from buf, starting at buffer offset
ofs. The data is written at offset file_offset from the beginning of
fd.
On Unix systems, the file descriptor position is unaffected. On Windows it is changed to be just after the last written position.
The promise can be rejected with any exception that can be raised by
write or lseek.
valwrite_string :file_descr->``string->``int->``int->``intLwt.t
See write.
valpwrite_string :file_descr->``string->``file_offset:int->``int->``int->``intLwt.t
See pwrite.
moduleIO_vectors:sig...end
Sequences of buffer slices for writev.
valreadv :file_descr->IO_vectors.t->``intLwt.t
readv fd vs reads bytes from fd into the buffer slices vs. If the
operation completes successfully, the resulting promise resolves to the
number of bytes read.
Data is always read directly into Bigarray slices. If the Unix file
descriptor underlying fd is in non-blocking mode, data is also read
directly into bytes slices. Otherwise, data for bytes slices is
first read into temporary buffers, then copied.
Note that the returned Lwt promise is pending until failure or a
successful read, even if the underlying file descriptor is in
non-blocking mode. See of_unix_file_descr
for a discussion of non-blocking I/O and Lwt.
If
IO_vectors.system_limit
is Some n and the count of slices in vs exceeds n, then
Lwt_unix.readv reads only into the first n slices of vs.
Not implemented on Windows. It should be possible to implement, upon request, for Windows sockets only.
See readv(3p).
- since 2.7.0
valwritev :file_descr->IO_vectors.t->``intLwt.t
writev fd vs writes the bytes in the buffer slices vs to the file
descriptor fd. If the operation completes successfully, the resulting
promise resolves to the number of bytes written.
If the Unix file descriptor underlying fd is in non-blocking mode,
writev does not make a copy the bytes before writing. Otherwise, it
copies bytes slices, but not Bigarray slices.
Note that the returned Lwt promise is pending until failure or a
successful write, even if the underlying descriptor is in non-blocking
mode. See of_unix_file_descr for a
discussion of non-blocking I/O and Lwt.
If
IO_vectors.system_limit
is Some n and the count of slices in vs exceeds n, then
Lwt_unix.writev passes only the first n slices in vs to the
underlying writev system call.
Not implemented on Windows. It should be possible to implement, upon request, for Windows sockets only.
The behavior of writev when vs has zero slices depends on the
system, and may change in future versions of Lwt. On Linux, writev
will succeed and write zero bytes. On BSD (including macOS), writev
will fail with Unix.Unix_error (Unix.EINVAL, "writev", ...).
See writev(3p).
- since 2.7.0
valreadable :file_descr->bool
Returns whether the given file descriptor is currently readable.
valwritable :file_descr->bool
Returns whether the given file descriptor is currently writable.
valwait_read :file_descr->``unitLwt.t
Waits (without blocking other promises) until there is something to read from the file descriptor.
Note that you don't need to use this function if you are using Lwt I/O functions for reading, since they provide non-blocking waiting automatically.
The intended use case for this function is interfacing with existing libraries that are known to be blocking.
valwait_write :file_descr->``unitLwt.t
Waits (without blocking other promises) until it is possible to write on the file descriptor.
Note that you don't need to use this function if you are using Lwt I/O functions for writing, since they provide non-blocking waiting automatically.
The intended use case for this function is interfacing with existing libraries that are known to be blocking.
Seeking and truncating
typeseek_command`` =Unix.seek_command=
|SEEK_SET
|SEEK_CUR
|SEEK_END
vallseek :file_descr->``int->seek_command->``intLwt.t
Wrapper for Unix.lseek
valtruncate : ``string->``int->``unitLwt.t
Wrapper for Unix.truncate
valftruncate :file_descr->``int->``unitLwt.t
Wrapper for Unix.ftruncate
Syncing
valfsync :file_descr->``unitLwt.t
Synchronise all data and metadata of the file descriptor with the disk.
On Windows it uses FlushFileBuffers.
valfdatasync :file_descr->``unitLwt.t
Synchronise all data (but not metadata) of the file descriptor with the disk.
Note that fdatasync is not available on Windows and OS X.
File status
typefile_kind`` =Unix.file_kind=
|S_REG
|S_DIR
|S_CHR
|S_BLK
|S_LNK
|S_FIFO
|S_SOCK
typestats`` =Unix.stats= ``{
st_dev : int;
st_ino : int;
st_kind :file_kind;
st_perm :file_perm;
st_nlink : int;
st_uid : int;
st_gid : int;
st_rdev : int;
st_size : int;
st_atime : float;
st_mtime : float;
st_ctime : float;}
Wrapper for Unix.lstat
valfstat :file_descr->statsLwt.t
Wrapper for Unix.fstat
valfile_exists : ``string->``boolLwt.t
file_exists name tests if a file named name exists.
Note that file_exists behaves similarly to Sys.file_exists:
-
“file” is interpreted as “directory entry” in this context
-
file_exists namewill returnfalsein circumstances that would makestatraise aUnix.Unix_errorexception.
valutimes : ``string->``float->``float->``unitLwt.t
utimes path atime mtime updates the access and modification times of
the file at path. The access time is set to atime and the
modification time to mtime. To set both to the current time, call
utimes path 0. 0..
This function corresponds to
Unix.utimes. See also
utimes(3p).
- since 2.6.0
valisatty :file_descr->``boolLwt.t
Wrapper for Unix.isatty
File operations on large files
moduleLargeFile:sig...end
Operations on file names
valunlink : ``string->``unitLwt.t
Wrapper for Unix.unlink
valrename : ``string->``string->``unitLwt.t
Wrapper for Unix.rename
File permissions and ownership
Wrapper for Unix.chmod
valfchmod :file_descr->file_perm->``unitLwt.t
Wrapper for Unix.fchmod
valchown : ``string->``int->``int->``unitLwt.t
Wrapper for Unix.chown
valfchown :file_descr->``int->``int->``unitLwt.t
Wrapper for Unix.fchown
typeaccess_permission`` =Unix.access_permission=
|R_OK
|W_OK
|X_OK
|F_OK
valaccess : ``string->access_permissionlist``->``unitLwt.t
Wrapper for Unix.access
Operations on file descriptors
valdup : ``?cloexec:bool->file_descr->file_descr
Wrapper for Unix.dup
valdup2 : ``?cloexec:bool->file_descr->file_descr->unit
Wrapper for Unix.dup2
valset_close_on_exec :file_descr->unit
Wrapper for
Unix.set_close_on_exec
valclear_close_on_exec :file_descr->unit
Wrapper for
Unix.clear_close_on_exec
Directories
Wrapper for Unix.mkdir
valrmdir : ``string->``unitLwt.t
Wrapper for Unix.rmdir
valchdir : ``string->``unitLwt.t
Wrapper for Unix.chdir
valgetcwd : ``unit->``stringLwt.t
Wrapper for Unix.getcwd
- since 3.1.0
valchroot : ``string->``unitLwt.t
Wrapper for Unix.chroot
typedir_handle`` =Unix.dir_handle
valopendir : ``string->dir_handleLwt.t
Opens a directory for listing. Directories opened with this function
must be explicitly closed with closedir. This is a
cooperative analog of Unix.opendir.
valreaddir :dir_handle->``stringLwt.t
Reads the next directory entry from the given directory. Special entries
such as . and .. are included. If all entries have been read, raises
End_of_file. This is a cooperative analog of
Unix.readdir.
valreaddir_n :dir_handle->``int->``string array``Lwt.t
readdir_n handle count reads at most count entries from the given
directory. It is more efficient than calling readdir count times. If
the length of the returned array is smaller than count, this means
that the end of the directory has been reached.
valrewinddir :dir_handle->``unitLwt.t
Resets the given directory handle, so that directory listing can be
restarted. Cooperative analog of
Unix.rewinddir.
valclosedir :dir_handle->``unitLwt.t
Closes a directory handle. Cooperative analog of
Unix.closedir.
valfiles_of_directory : ``string->``stringLwt_stream.t
files_of_directory dir returns the stream of all files of dir.
Pipes and redirections
valpipe : ``?cloexec:bool->``unit->file_descr*file_descr
pipe () creates pipe using Unix.pipe
and returns two lwt file descriptors created from unix
file_descriptor
valpipe_in : ``?cloexec:bool->``unit->file_descr*Unix.file_descr
pipe_in () is the same as pipe but maps only the unix
file descriptor for reading into a lwt one. The second is not put
into non-blocking mode. You usually want to use this before forking to
receive data from the child process.
valpipe_out : ``?cloexec:bool->``unit->Unix.file_descr*file_descr
pipe_out () is the inverse of pipe_in. You usually
want to use this before forking to send data to the child process
Wrapper for Unix.mkfifo
Symbolic links
valsymlink : ``?to_dir:bool->``string->``string->``unitLwt.t
Wrapper for Unix.symlink
valreadlink : ``string->``stringLwt.t
Wrapper for Unix.readlink
Locking
typelock_command`` =Unix.lock_command=
|F_ULOCK
|F_LOCK
|F_TLOCK
|F_TEST
|F_RLOCK
|F_TRLOCK
vallockf :file_descr->lock_command->``int->``unitLwt.t
Wrapper for Unix.lockf
User id, group id
typepasswd_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;}
typegroup_entry`` =Unix.group_entry= ``{
gr_name : string;
gr_passwd : string;
gr_gid : int;
gr_mem : ``string array``;}
valgetlogin : ``unit->``stringLwt.t
Wrapper for Unix.getlogin
valgetpwnam : ``string->passwd_entryLwt.t
Wrapper for Unix.getpwnam
valgetgrnam : ``string->group_entryLwt.t
Wrapper for Unix.getgrnam
valgetpwuid : ``int->passwd_entryLwt.t
Wrapper for Unix.getpwuid
valgetgrgid : ``int->group_entryLwt.t
Wrapper for Unix.getgrgid
Signals
typesignal_handler_id
Id of a signal handler, used to cancel it
valon_signal : ``int->``(``int->unit)``->signal_handler_id
on_signal signum f calls f each time the signal with numnber
signum is received by the process. It returns a signal handler
identifier that can be used to stop monitoring signum.
valon_signal_full : ``int->``(signal_handler_id->``int->unit)``->signal_handler_id
on_signal_full f is the same as on_signal f except that f also
receive the signal handler identifier as argument so it can disable it.
valdisable_signal_handler :signal_handler_id->unit
Stops receiving this signal
valsignal_count : ``unit->int
Returns the number of registered signal handler.
valreinstall_signal_handler : ``int->unit
reinstall_signal_handler signum if any signal handler is registered
for this signal with on_signal, it reinstall the
signal handler (with Sys.set_signal). This is useful in case another
part of the program install another signal handler.
Sockets
typeinet_addr`` =Unix.inet_addr
typesocket_domain`` =Unix.socket_domain=
|PF_UNIX
|PF_INET
|PF_INET6
typesocket_type`` =Unix.socket_type=
|SOCK_STREAM
|SOCK_DGRAM
|SOCK_RAW
|SOCK_SEQPACKET
typesockaddr`` =Unix.sockaddr=
|ADDR_UNIXofstring
|ADDR_INETofinet_addr* int
valsocket : ``?cloexec:bool->socket_domain->socket_type->``int->file_descr
socket domain type proto is the same as
Unix.socket but maps the result into
a lwt file descriptor
valsocketpair : ``?cloexec:bool->socket_domain->socket_type->``int->file_descr*file_descr
Wrapper for Unix.socketpair
valbind :file_descr->sockaddr->``unitLwt.t
vallisten :file_descr->``int->unit
Wrapper for Unix.listen
valaccept : ``?cloexec:bool->file_descr->``(file_descr*sockaddr)``Lwt.t
Wrapper for Unix.accept
valaccept_n : ``?cloexec:bool->file_descr->``int->``(``(file_descr*sockaddr)`` list`` * ``exn option``)``Lwt.t
accept_n fd count accepts up to count connections at one time.
-
if no connection is available right now, it returns a pending promise
-
if more than 1 and less than
countare available, it returns all of them -
if more than
countare available, it returns the nextcountof them -
if an error happens, it returns the connections that have been successfully accepted so far and the error
accept_n has the advantage of improving performance. If you want a
more detailed description, you can have a look at:
valconnect :file_descr->sockaddr->``unitLwt.t
Wrapper for Unix.connect
typeshutdown_command`` =Unix.shutdown_command=
|SHUTDOWN_RECEIVE
|SHUTDOWN_SEND
|SHUTDOWN_ALL
valshutdown :file_descr->shutdown_command->unit
Wrapper for Unix.shutdown
valgetsockname :file_descr->sockaddr
Wrapper for Unix.getsockname
valgetpeername :file_descr->sockaddr
Wrapper for Unix.getpeername
typemsg_flag`` =Unix.msg_flag=
|MSG_OOB
|MSG_DONTROUTE
|MSG_PEEK
valrecv :file_descr->``bytes->``int->``int->msg_flaglist``->``intLwt.t
Wrapper for Unix.recv.
On Windows, recv writes data into a temporary buffer, then copies it
into the given one.
valrecvfrom :file_descr->``bytes->``int->``int->msg_flaglist``->``(int *sockaddr)``Lwt.t
Wrapper for Unix.recvfrom.
On Windows, recvfrom writes data into a temporary buffer, then copies
it into the given one.
valsend :file_descr->``bytes->``int->``int->msg_flaglist``->``intLwt.t
Wrapper for Unix.send.
On Windows, send copies the given buffer before writing.
valsendto :file_descr->``bytes->``int->``int->msg_flaglist``->sockaddr->``intLwt.t
Wrapper for Unix.sendto.
On Windows, sendto copies the given buffer before writing.
valrecv_msg : ``socket:file_descr->``io_vectors:IO_vectors.t->``(int *Unix.file_descrlist``)``Lwt.t
recv_msg ~socket ~io_vectors receives data into a list of io-vectors,
plus any file-descriptors that may accompany the messages. It returns a
tuple whose first field is the number of bytes received and second is a
list of received file descriptors. The messages themselves will be
recorded in the provided io_vectors list. Data is written directly
into the iov_buffer buffers.
Not implemented on Windows.
- since 5.0.0
valsend_msg : ``socket:file_descr->``io_vectors:IO_vectors.t->``fds:Unix.file_descrlist``->``intLwt.t
send_msg ~socket ~io_vectors ~fds sends data from a list of
io-vectors, accompanied with a list of file-descriptors. It returns the
number of bytes sent. If fd-passing is not possible on the current
system and fds is not empty, it raises
Lwt_sys.Not_available "fd_passing". Data is written directly from the
io_vectors buffers.
Not implemented on Windows.
- since 5.0.0
valsend_msgto : ``socket:file_descr->``io_vectors:IO_vectors.t->``fds:Unix.file_descrlist``->``dest:Unix.sockaddr->``intLwt.t
send_msgto ~socket ~io_vectors ~fds ~dest is similar to send_msg but
takes an additional dest argument to set the address when using a
connection-less socket.
Not implemented on Windows.
- since 5.4.0
typecredentials`` = ``{
cred_pid : int;
cred_uid : int;
cred_gid : int;}
valget_credentials :file_descr->credentials
get_credentials fd returns credentials information from the given
socket. On some platforms, obtaining the peer pid is not possible and it
will be set to -1. If obtaining credentials is not possible on the
current system, it raises Lwt_sys.Not_available "get_credentials".
This call is not available on windows.
Socket options
typesocket_bool_option`` =Unix.socket_bool_option=
|SO_DEBUG
|SO_BROADCAST
|SO_REUSEADDR
|SO_KEEPALIVE
|SO_DONTROUTE
|SO_OOBINLINE
|SO_ACCEPTCONN
|TCP_NODELAY
|IPV6_ONLY
|SO_REUSEPORT
typesocket_int_option`` =Unix.socket_int_option=
|SO_SNDBUF
|SO_RCVBUF
|SO_ERROR(*
- deprecated Use Unix.getsockopt_error instead.
*)
|SO_TYPE
|SO_RCVLOWAT
|SO_SNDLOWAT
typesocket_optint_option`` =Unix.socket_optint_option=
|SO_LINGER
typesocket_float_option`` =Unix.socket_float_option=
|SO_RCVTIMEO
|SO_SNDTIMEO(* Note: these options are provided for the sake of completeness only. Lwt places all sockets in non-blocking mode, for which these options are meaningless. Use
Lwt.pickwithLwt_unix.sleeporLwt_unix.timeoutfor timeouts.*)
valgetsockopt :file_descr->socket_bool_option->bool
Wrapper for Unix.getsockopt
valsetsockopt :file_descr->socket_bool_option->``bool->unit
Wrapper for Unix.setsockopt
valgetsockopt_int :file_descr->socket_int_option->int
Wrapper for
Unix.getsockopt_int
valsetsockopt_int :file_descr->socket_int_option->``int->unit
Wrapper for
Unix.setsockopt_int
valgetsockopt_optint :file_descr->socket_optint_option->``int option
Wrapper for
Unix.getsockopt_optint
valsetsockopt_optint :file_descr->socket_optint_option->``int option``->unit
Wrapper for
Unix.setsockopt_optint
valgetsockopt_float :file_descr->socket_float_option->float
Wrapper for
Unix.getsockopt_float
valsetsockopt_float :file_descr->socket_float_option->``float->unit
Wrapper for
Unix.setsockopt_float
valgetsockopt_error :file_descr->Unix.erroroption
Wrapper for
Unix.getsockopt_error
Multicast functions
valmcast_set_loop :file_descr->``bool->unit
Whether sent multicast messages are received by the sending host
valmcast_set_ttl :file_descr->``int->unit
Set TTL/hops value
valmcast_add_membership :file_descr->``?ifname:Unix.inet_addr->Unix.inet_addr->unit
mcast_add_membership fd ~ifname addr joins the multicast group addr
on the network interface ifname.
valmcast_drop_membership :file_descr->``?ifname:Unix.inet_addr->Unix.inet_addr->unit
mcast_drop_membership fd ~ifname addr leaves the multicast group
addr on the network interface ifname.
Host and protocol databases
typehost_entry`` =Unix.host_entry= ``{
h_name : string;
h_aliases : ``string array``;
h_addrtype :socket_domain;
h_addr_list :inet_addrarray``;}
typeprotocol_entry`` =Unix.protocol_entry= ``{
p_name : string;
p_aliases : ``string array``;
p_proto : int;}
typeservice_entry`` =Unix.service_entry= ``{
s_name : string;
s_aliases : ``string array``;
s_port : int;
s_proto : string;}
valgethostname : ``unit->``stringLwt.t
Wrapper for Unix.gethostname
valgethostbyname : ``string->host_entryLwt.t
Wrapper for Unix.gethostbyname
valgethostbyaddr :inet_addr->host_entryLwt.t
Wrapper for Unix.gethostbyaddr
valgetprotobyname : ``string->protocol_entryLwt.t
Wrapper for
Unix.getprotobyname
valgetprotobynumber : ``int->protocol_entryLwt.t
Wrapper for
Unix.getprotobynumber
valgetservbyname : ``string->``string->service_entryLwt.t
Wrapper for Unix.getservbyname
valgetservbyport : ``int->``string->service_entryLwt.t
Wrapper for Unix.getservbyport
typeaddr_info`` =Unix.addr_info= ``{
ai_family :socket_domain;
ai_socktype :socket_type;
ai_protocol : int;
ai_addr :sockaddr;
ai_canonname : string;}
typegetaddrinfo_option`` =Unix.getaddrinfo_option=
|AI_FAMILYofsocket_domain
|AI_SOCKTYPEofsocket_type
|AI_PROTOCOLofint
|AI_NUMERICHOST
|AI_CANONNAME
|AI_PASSIVE
valgetaddrinfo : ``string->``string->getaddrinfo_optionlist``->addr_infolist``Lwt.t
Wrapper for Unix.getaddrinfo
typename_info`` =Unix.name_info= ``{
ni_hostname : string;
ni_service : string;}
typegetnameinfo_option`` =Unix.getnameinfo_option=
|NI_NOFQDN
|NI_NUMERICHOST
|NI_NAMEREQD
|NI_NUMERICSERV
|NI_DGRAM
valgetnameinfo :sockaddr->getnameinfo_optionlist``->name_infoLwt.t
Wrapper for Unix.getnameinfo
Terminal interface
typeterminal_io`` =Unix.terminal_io= ``{
mutablec_ignbrk : bool;
mutablec_brkint : bool;
mutablec_ignpar : bool;
mutablec_parmrk : bool;
mutablec_inpck : bool;
mutablec_istrip : bool;
mutablec_inlcr : bool;
mutablec_igncr : bool;
mutablec_icrnl : bool;
mutablec_ixon : bool;
mutablec_ixoff : bool;
mutablec_opost : bool;
mutablec_obaud : int;
mutablec_ibaud : int;
mutablec_csize : int;
mutablec_cstopb : int;
mutablec_cread : bool;
mutablec_parenb : bool;
mutablec_parodd : bool;
mutablec_hupcl : bool;
mutablec_clocal : bool;
mutablec_isig : bool;
mutablec_icanon : bool;
mutablec_noflsh : bool;
mutablec_echo : bool;
mutablec_echoe : bool;
mutablec_echok : bool;
mutablec_echonl : bool;
mutablec_vintr : char;
mutablec_vquit : char;
mutablec_verase : char;
mutablec_vkill : char;
mutablec_veof : char;
mutablec_veol : char;
mutablec_vmin : int;
mutablec_vtime : int;
mutablec_vstart : char;
mutablec_vstop : char;}
valtcgetattr :file_descr->terminal_ioLwt.t
Wrapper for Unix.tcgetattr
typesetattr_when`` =Unix.setattr_when=
|TCSANOW
|TCSADRAIN
|TCSAFLUSH
valtcsetattr :file_descr->setattr_when->terminal_io->``unitLwt.t
Wrapper for Unix.tcsetattr
valtcsendbreak :file_descr->``int->``unitLwt.t
Wrapper for Unix.tcsendbreak
valtcdrain :file_descr->``unitLwt.t
Wrapper for Unix.tcdrain
typeflush_queue`` =Unix.flush_queue=
|TCIFLUSH
|TCOFLUSH
|TCIOFLUSH
valtcflush :file_descr->flush_queue->``unitLwt.t
Wrapper for Unix.tcflush
typeflow_action`` =Unix.flow_action=
|TCOOFF
|TCOON
|TCIOFF
|TCION
valtcflow :file_descr->flow_action->``unitLwt.t
Wrapper for Unix.tcflow
Configuration (deprecated)
typeasync_method`` =
|Async_none(* System calls are made synchronously, and may block the entire program.
*)
|Async_detach(* System calls are made in another system thread, thus without blocking other Lwt promises. The drawback is that it may degrade performance in some cases.
This is the default.
*)
|Async_switch(*
deprecated
A synonym for
Async_detach. This was a different method in the past.*)
For system calls that cannot be made asynchronously, Lwt uses one of the following method:
valdefault_async_method : ``unit->async_method
Returns the default async method.
This can be initialized using the environment variable
"LWT_ASYNC_METHOD" with possible values "none", "detach" and
"switch".
-
deprecated
Will always return
Async_detachin Lwt 5.0.0.
valset_default_async_method :async_method->unit
Sets the default async method.
-
deprecated
Will be a no-op in Lwt 5.0.0.
valasync_method : ``unit->async_method
async_method () returns the async method used in the current thread.
-
deprecated
Will always return
Async_detachin Lwt 5.0.0.
valasync_method_key :async_methodLwt.key
The key for storing the local async method.
-
deprecated
Will be ignored in Lwt 5.0.0.
valwith_async_none : ``(``unit->'a)``->'a
with_async_none f is a shorthand for:
Lwt.with_value async_method_key (Some Async_none) f-
deprecated
Will have no effect in Lwt 5.0.0.
valwith_async_detach : ``(``unit->'a)``->'a
with_async_detach f is a shorthand for:
Lwt.with_value async_method_key (Some Async_detach) f-
deprecated
Will have no effect in Lwt 5.0.0.
valwith_async_switch : ``(``unit->'a)``->'a
with_async_switch f is a shorthand for:
Lwt.with_value async_method_key (Some Async_switch) f-
deprecated
Will have no effect in Lwt 5.0.0.
Low-level interaction
exceptionRetry
If an action raises Retry, it will be requeued
until the file descriptor becomes readable/writable again.
exceptionRetry_read
If an action raises Retry_read, it will be
requeued until the file descriptor becomes readable.
exceptionRetry_write
If an action raises Retry_read, it will be
requeued until the file descriptor becomes writables.
typeio_event`` =
|Read
|Write
valwrap_syscall :io_event->file_descr->``(``unit->'a)``->'aLwt.t
wrap_syscall set fd action wrap an action on a file descriptor. It
tries to execute action, and if it can not be performed immediately
without blocking, it is registered for later.
In the latter case, if the promise is canceled, action is removed from
set.
valcheck_descriptor :file_descr->unit
check_descriptor fd raise an exception if fd is not in the state
Open.
valregister_action :io_event->file_descr->``(``unit->'a)``->'aLwt.t
register_action set fd action registers action on fd. When fd
becomes readable/writable action is called.
Note:
-
you must call
check_descriptor fdbefore callingregister_action -
you should prefer using
wrap_syscall
type``'a job
Type of job descriptions. A job description describe how to call a C function and how to get its result. The C function may be executed in another system thread.
valrun_job : ``?async_method:async_method->'ajob->'aLwt.t
run_job ?async_method job starts job and wait for its termination.
The ~async_method argument will be ignored in Lwt 5.0.0, and this
function will always act as if ~async_method:Async_detach is passed.
The async method is chosen follow:
- if the optional parameter
async_methodis specified, it is used, - otherwise if the local key
async_method_keyis set in the current thread, it is used, - otherwise the default method (returned by
default_async_method) is used.
If the method is Async_none then the job is run synchronously and may
block the current system thread, thus blocking all Lwt threads.
If the method is Async_detach then the job is run in another system
thread, unless the the maximum number of worker threads has been reached
(as given by pool_size).
If the method is Async_switch then the job is run synchronously and if
it blocks, execution will continue in another system thread (unless the
limit is reached).
valabort_jobs : ``exn->unit
abort_jobs exn make all pending jobs to fail with exn. Note that this
does not abort the real job (i.e. the C function executing it), just the
lwt thread for it.
valcancel_jobs : ``unit->unit
cancel_jobs () is the same as abort_jobs Lwt.Canceled.
valwait_for_jobs : ``unit->``unitLwt.t
Wait for all pending jobs to terminate.
valexecute_job : ``?async_method:async_method->``job:'ajob->``result:``('ajob->'b)``->``free:``('ajob->unit)``->'bLwt.t
-
deprecated
Use
run_job.
Notifications
Lwt internally use a pipe to send notification to the main thread. The following functions allow to use this pipe.
valmake_notification : ``?once:bool->``(``unit->unit)``->int
make_notification ?once f registers a new notifier. It returns the id
of the notifier. Each time a notification with this id is received, f
is called.
if once is specified, then the notification is stopped after the first
time it is received. It defaults to false.
valsend_notification : ``int->unit
send_notification id sends a notification.
This function is thread-safe.
valstop_notification : ``int->unit
Stop the given notification. Note that you should not reuse the id after the notification has been stopped, the result is unspecified if you do so.
valcall_notification : ``int->unit
Call the handler associated to the given notification. Note that if the
notification was defined with once = true it is removed.
valset_notification : ``int->``(``unit->unit)``->unit
set_notification id f replace the function associated to the
notification by f. It raises Not_found if the given notification is
not found.
System threads pool
If the program is using the async method Async_detach or
Async_switch, Lwt will launch system threads to execute blocking
system calls asynchronously.
valpool_size : ``unit->int
Maximum number of system threads that can be started. If this limit is reached, jobs will be executed synchronously.
valset_pool_size : ``int->unit
Change the size of the pool.
valthread_count : ``unit->int
The number of system threads running (excluding this one).
valthread_waiting_count : ``unit->int
The number threads waiting for a job.
CPUs
valget_cpu : ``unit->int
get_cpu () returns the number of the CPU the current thread is running
on.
valget_affinity : ``?pid:int->``unit->``int list
get_affinity ?pid () returns the list of CPUs the process with pid
pid is allowed to run on. If pid is not specified then the affinity
of the current process is returned.
valset_affinity : ``?pid:int->``int list``->unit
set_affinity ?pid cpus sets the list of CPUs the given process is
allowed to run on.
Versioned interfaces
moduleVersioned:sig...end
Versioned variants of APIs undergoing breaking changes.
