Module Lwt_io
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 "= 5.6.1" FINDLIBS lwt lwt.unix) DkSDKProject_MakeAvailable(lwt)
- Add the - Findlib::lwtlibrary to any desired targets in- src/*/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.5.6.1
- Edit your - dune-projectand add:- (package (name YourExistingPackage) (depends ; ... existing dependenices ... (lwt (>= 5.6.1))))- Then run: - dune build *.opam # if this fails, run: dune build
- Edit your - <package>.opamfile and add:- depends: [ # ... existing dependencies ... "lwt" {>= "5.6.1"} ]- 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))A channel is a high-level object for performing input/output (IO). It allows to read/write from/to the outside world in an efficient way, by minimising the number of system calls.
An output channel is used to send data and an input channel is used to receive data.
If you are familiar with buffered channels you may be familiar too with the flush operation. Note that byte channels of this module are automatically flushed when there is nothing else to do (i.e. before the program becomes idle), so this means that you no longer have to write:
eprintf "log message\n";
flush stderr;to have your messages displayed.
Note about errors: input functions of this module raise End_of_file
when the end-of-file is reached (i.e. when the read function returns
0). Other exceptions are ones caused by the backend read/write
functions, such as
Unix.Unix_error.
exceptionChannel_closedofstring
Exception raised when a channel is closed. The parameter is a description of the channel.
Types
type``'mode channel
Type of buffered byte channels
typeinput
Input mode
typeoutput
Output mode
Well-known instances
valstdin :input_channel
The standard input, it reads data from
Lwt_unix.stdin
valstdout :output_channel
The standard output, it writes data to
Lwt_unix.stdout
valstderr :output_channel
The standard output for error messages, it writes data to
Lwt_unix.stderr
valzero :input_channel
Inputs which returns always '\x00'
valnull :output_channel
Output which drops everything
Channels creation/manipulation
valpipe : ``?cloexec:bool->``?in_buffer:Lwt_bytes.t->``?out_buffer:Lwt_bytes.t->``unit->input_channel*output_channel
pipe ?cloexec ?in_buffer ?out_buffer () creates a pipe using
Lwt_unix.pipe and makes two channels from
the two returned file descriptors
valmake : ``?buffer:Lwt_bytes.t->``?close:``(``unit->``unitLwt.t)``->``?seek:``(``int64->Unix.seek_command->``int64Lwt.t)``->``mode:'modemode->``(Lwt_bytes.t->``int->``int->``intLwt.t)``->'modechannel
make ?buffer ?close ~mode perform_io is the main function for creating
new channels.
- 
parameter buffer user-supplied buffer. When this argument is present, its value will be used as the buffer for the created channel. The size of buffer must conform to the limitations described in set_default_buffer_size. When this argument is not present, a new internal buffer of default size will be allocated for this channel.Warning: do not use the same buffer for simultaneous work with more than one channel. There are other functions in this module that take a bufferargument, sharing the same semantics.
- 
parameter close close function of the channel. It defaults to Lwt.return
- 
parameter seek same meaning as Unix.lseek
- 
parameter mode 
- 
parameter perform_io is the read or write function. It is called when more input is needed or when the buffer need to be flushed. 
valof_bytes : ``mode:'modemode->Lwt_bytes.t->'modechannel
Create a channel from a byte array. Reading/writing is done directly on the provided array.
valof_fd : ``?buffer:Lwt_bytes.t->``?close:``(``unit->``unitLwt.t)``->``mode:'modemode->Lwt_unix.file_descr->'modechannel
of_fd ?buffer ?close ~mode fd creates a channel from a file
descriptor.
- 
parameter close defaults to closing the file descriptor. 
valof_unix_fd : ``?buffer:Lwt_bytes.t->``?close:``(``unit->``unitLwt.t)``->``mode:'modemode->Unix.file_descr->'modechannel
of_unix_fd ?buffer ?close ~mode fd is a short-hand for:
of_fd ?buffer ?close (Lwt_unix.of_unix_file_descr fd)
close ch closes the given channel. If ch is an output channel, it
performs all pending actions, flushes it and closes it. If ch is an
input channel, it just closes it immediately.
close returns the result of the close function of the channel.
Multiple calls to close will return exactly the same value.
Note: you cannot use close on channels obtained with
atomic.
abort ch abort current operations and close the channel immediately.
atomic f transforms a sequence of io operations into one single atomic
io operation.
Note:
- the channel passed to fis invalid afterfterminates
- atomiccan be called inside another- atomic
valfile_length : ``string->``int64Lwt.t
Retrieves the length of the file at the given path. If the path refers
to a directory, the returned promise is rejected with
Unix.(Unix_error (EISDIR, _, _)).
valbuffered :'achannel->int
buffered oc returns the number of bytes in the buffer
valflush :output_channel->``unitLwt.t
flush oc performs all pending writes on oc
valflush_all : ``unit->``unitLwt.t
flush_all () flushes all open output channels
valbuffer_size :'achannel->int
Returns the size of the internal buffer.
valis_busy :'achannel->bool
is_busy channel returns whether the given channel is currently busy. A
channel is busy when there is at least one job using it that has not yet
terminated.
valis_closed :'achannel->bool
is_closed channel returns whether the given channel is currently
closed.
- since 4.2.0
Random access
valposition :'achannel->int64
position ch Returns the current position in the channel.
set_position ch pos Sets the position in the output channel. This does
not work if the channel does not support random access.
Reading
Note: except for functions dealing with streams
(read_chars and read_lines)
all functions are atomic.
valread_char :input_channel->``charLwt.t
read_char ic reads the next character of ic.
- 
raises End_of_file if the end of the file is reached 
valread_char_opt :input_channel->``char option``Lwt.t
Same as Lwt_io.read_char, but does not raise
End_of_file on end of input
valread_chars :input_channel->``charLwt_stream.t
read_chars ic returns a stream holding all characters of ic
valread_line :input_channel->``stringLwt.t
read_line ic reads one complete line from ic and returns it without
the end of line. End of line is either "\n" or "\r\n".
If the end of input is reached before reading any character,
End_of_file is raised. If it is reached before reading an end of line
but characters have already been read, they are returned.
valread_line_opt :input_channel->``string option``Lwt.t
Same as read_line but do not raise End_of_file on
end of input.
valread_lines :input_channel->``stringLwt_stream.t
read_lines ic returns a stream holding all lines of ic
valread : ``?count:int->input_channel->``stringLwt.t
If ~count is specified, read ~count ic reads at most ~count bytes
from ic in one read operation. Note that fewer than ~count bytes can
be read. This can happen for multiple reasons, including end of input,
or no more data currently available. Check the size of the resulting
string. read resolves with "" if the input channel is already at the
end of input.
If ~count is not specified, read ic reads all bytes until the end of
input.
valread_into :input_channel->``bytes->``int->``int->``intLwt.t
read_into ic buffer offset length reads up to length bytes, stores
them in buffer at offset offset, and returns the number of bytes
read.
Note: read_into does not raise End_of_file, it returns a length of
0 instead.
valread_into_exactly :input_channel->``bytes->``int->``int->``unitLwt.t
read_into_exactly ic buffer offset length reads exactly length bytes
and stores them in buffer at offset offset.
- 
raises End_of_file on end of input 
valread_into_bigstring :input_channel->Lwt_bytes.t->``int->``int->``intLwt.t
valread_into_exactly_bigstring :input_channel->Lwt_bytes.t->``int->``int->``unitLwt.t
valread_value :input_channel->'aLwt.t
read_value channel reads a marshaled value from channel; it
corresponds to the standard library's
Stdlib.Marshal.from_channel.
The corresponding writing function is write_value.
Note that reading marshaled values is not, in general, type-safe. See
the warning in the description of module
Stdlib.Marshal for details. The short
version is: if you read a value of one type, such as string, when a
value of another type, such as int has actually been marshaled to
channel, you may get arbitrary behavior, including segmentation
faults, access violations, security bugs, etc.
Writing
Note: as for reading functions, all functions except
write_chars and write_lines
are atomic.
For example if you use write_line in two different
threads, the two operations will be serialized, and lines cannot be
mixed.
valwrite_char :output_channel->``char->``unitLwt.t
write_char oc char writes char on oc
valwrite_chars :output_channel->``charLwt_stream.t->``unitLwt.t
write_chars oc chars writes all characters of chars on oc
valwrite :output_channel->``string->``unitLwt.t
write oc str writes all characters of str on oc
valwrite_line :output_channel->``string->``unitLwt.t
write_line oc str writes str on oc followed by a new-line.
valwrite_lines :output_channel->``stringLwt_stream.t->``unitLwt.t
write_lines oc lines writes all lines of lines to oc
valwrite_from :output_channel->``bytes->``int->``int->``intLwt.t
write_from oc buffer offset length writes up to length bytes to
oc, from buffer at offset offset and returns the number of bytes
actually written
valwrite_from_bigstring :output_channel->Lwt_bytes.t->``int->``int->``intLwt.t
valwrite_from_string :output_channel->``string->``int->``int->``intLwt.t
See write.
valwrite_from_exactly :output_channel->``bytes->``int->``int->``unitLwt.t
write_from_exactly oc buffer offset length writes all length bytes
from buffer at offset offset to oc
valwrite_from_exactly_bigstring :output_channel->Lwt_bytes.t->``int->``int->``unitLwt.t
valwrite_from_string_exactly :output_channel->``string->``int->``int->``unitLwt.t
See write_from_exactly.
valwrite_value :output_channel->``?flags:Stdlib.Marshal.extern_flagslist``->'a->``unitLwt.t
write_value channel ?flags v writes v to channel using the
Marshal module of the standard library. See
Stdlib.Marshal.to_channel
for an explanation of ?flags.
The corresponding reading function is read_value.
See warnings about type safety in the description of
read_value.
Printing
These functions are basically helpers. Also you may prefer using the
name printl rather than write_line
because it is shorter.
The general name of a printing function is <prefix>print<suffixes>,
where <prefix> is one of:
- 'f', which means that the function takes as argument a channel
- nothing, which means that the function prints on
stdout
- 'e', which means that the function prints on- stderr
and <suffixes> is a combination of:
- 'l'which means that a new-line character is printed after the message
- 'f'which means that the function takes as argument a format instead of a string
valfprint :output_channel->``string->``unitLwt.t
valfprintl :output_channel->``string->``unitLwt.t
valfprintf :output_channel->``('a, unit, string, ``unitLwt.t)``format4->'a
%! does nothing here. To flush the channel, use
Lwt_io.flush channel.
valfprintlf :output_channel->``('a, unit, string, ``unitLwt.t)``format4->'a
%! does nothing here. To flush the channel, use
Lwt_io.flush channel.
valprint : ``string->``unitLwt.t
valprintl : ``string->``unitLwt.t
%! does nothing here. To flush the channel, use
Lwt_io.(flush stdout).
%! does nothing here. To flush the channel, use
Lwt_io.(flush stdout).
valeprint : ``string->``unitLwt.t
valeprintl : ``string->``unitLwt.t
%! does nothing here. To flush the channel, use
Lwt_io.(flush stderr).
%! does nothing here. To flush the channel, use
Lwt_io.(flush stderr).
Utilities
valhexdump_stream :output_channel->``charLwt_stream.t->``unitLwt.t
hexdump_stream oc byte_stream produces the same output as the command
hexdump -C.
valhexdump :output_channel->``string->``unitLwt.t
hexdump oc str = hexdump_stream oc (Lwt_stream.of_string str)
File utilities
typefile_name`` = string
Type of file names
valopen_file : ``?buffer:Lwt_bytes.t->``?flags:Unix.open_flaglist``->``?perm:Unix.file_perm->``mode:'amode->file_name->'achannelLwt.t
Lwt_io.open_file ~mode file opens the given file, either for reading
(with ~mode:Input) or for writing (with ~mode:Output). The returned
channel provides buffered I/O on the file.
If ~buffer is supplied, it is used as the I/O buffer.
If ~flags is supplied, the file is opened with the given flags (see
Unix.open_flag). Note that
~flags is used exactly as given. For example, opening a file with
~flags and ~mode:Input does not implicitly add O_RDONLY. So, you
should include O_RDONLY when opening for reading (~mode:Input), and
O_WRONLY when opening for writing (~mode:Input). It is also
recommended to include O_NONBLOCK, unless you are sure that the file
cannot be a socket or a named pipe.
The default permissions used for creating new files are 0o666, i.e.
reading and writing are allowed for the file owner, group, and everyone.
These default permissions can be overridden by supplying ~perm.
Note: if opening for writing (~mode:Output), and the file already
exists, open_file truncates (clears) the file by default. If you would
like to keep the pre-existing contents of the file, use the ~flags
parameter to pass a custom flags list that does not include
Unix.open_flag.O_TRUNC.
- 
raises Unix.Unix_error on error. 
valwith_file : ``?buffer:Lwt_bytes.t->``?flags:Unix.open_flaglist``->``?perm:Unix.file_perm->``mode:'amode->file_name->``('achannel->'bLwt.t)``->'bLwt.t
Lwt_io.with_file ~mode filename f opens the given using
Lwt_io.open_file, and passes the resulting channel
to f. Lwt_io.with_file ensures that the channel is closed when the
promise returned by f resolves, or if f raises an exception.
See Lwt_io.open_file for a description of the
arguments, warnings, and other notes.
valopen_temp_file : ``?buffer:Lwt_bytes.t->``?flags:Unix.open_flaglist``->``?perm:Unix.file_perm->``?temp_dir:string->``?prefix:string->``?suffix:string->``unit->``(string *output_channel)``Lwt.t
open_temp_file () starts creating a new temporary file, and evaluates
to a promise for the pair of the file's name, and an output channel for
writing to the file.
The caller should take care to delete the file later. Alternatively, see
Lwt_io.with_temp_file.
The ?buffer and ?perm arguments are passed directly to an internal
call to Lwt_io.open_file.
If not specified, ?flags defaults to
[O_CREATE; O_EXCL; O_WRONLY; O_CLOEXEC]. If specified, the specified
flags are used exactly. Note that these should typically contain at
least O_CREAT and O_EXCL, otherwise open_temp_file may open an
existing file.
?temp_dir can be used to choose the directory in which the file is
created. For the current directory, use
Stdlib.Filename.current_dir_name.
If not specified, the directory is taken from
Stdlib.Filename.get_temp_dir_name,
which is typically set to your system temporary file directory.
?prefix helps determine the name of the file. It will be the prefix
concatenated with a random sequence of characters. If not specified,
open_temp_file uses some default prefix.
?suffix is like prefix, but it is appended at the end of the
filename. In particular, it can be used to set the extension. This
argument is supported since Lwt 4.4.0.
- since 3.2.0
valwith_temp_file : ``?buffer:Lwt_bytes.t->``?flags:Unix.open_flaglist``->``?perm:Unix.file_perm->``?temp_dir:string->``?prefix:string->``?suffix:string->``(``(string *output_channel)``->'bLwt.t)``->'bLwt.t
with_temp_file f calls open_temp_file (),
passing all optional arguments directly to it. It then attaches f to
run after the file is created, passing the filename and output channel
to f. When the promise returned by f is resolved, with_temp_file
closes the channel and deletes the temporary file by calling
Lwt_unix.unlink.
- since 3.2.0
valcreate_temp_dir : ``?perm:Unix.file_perm->``?parent:string->``?prefix:string->``?suffix:string->``unit->``stringLwt.t
Creates a temporary directory, and returns a promise that resolves to
its path. The caller must take care to remove the directory.
Alternatively, see Lwt_io.with_temp_dir.
If ~perm is specified, the directory is created with the given
permissions. The default permissions are 0755.
~parent is the directory in which the temporary directory is created.
If not specified, the default value is the result of
Filename.get_temp_dir_name ().
~prefix is prepended to the directory name, and ~suffix is appended
to it.
- since 4.4.0
valwith_temp_dir : ``?perm:Unix.file_perm->``?parent:string->``?prefix:string->``?suffix:string->``(``string->'aLwt.t)``->'aLwt.t
with_temp_dir f first calls create_temp_dir,
forwarding all optional arguments to it. Once the temporary directory is
created at path, with_temp_dir f calls f path. When the promise
returned by f path is resolved, with_temp_dir f recursively deletes
the temporary directory and all its contents.
- since 4.4.0
valopen_connection : ``?fd:Lwt_unix.file_descr->``?in_buffer:Lwt_bytes.t->``?out_buffer:Lwt_bytes.t->Unix.sockaddr->``(input_channel*output_channel)``Lwt.t
open_connection ?fd ?in_buffer ?out_buffer addr opens a connection to
the given address and returns two channels for using it. If fd is not
specified, a fresh one will be used.
The connection is completely closed when you close both channels.
- 
raises Unix.Unix_error on error. 
valwith_connection : ``?fd:Lwt_unix.file_descr->``?in_buffer:Lwt_bytes.t->``?out_buffer:Lwt_bytes.t->Unix.sockaddr->``(``(input_channel*output_channel)``->'aLwt.t)``->'aLwt.t
with_connection ?fd ?in_buffer ?out_buffer addr f opens a connection
to the given address and passes the channels to f
typeserver
Type of a server
valestablish_server_with_client_socket : ``?server_fd:Lwt_unix.file_descr->``?backlog:int->``?no_close:bool->Unix.sockaddr->``(Lwt_unix.sockaddr->Lwt_unix.file_descr->``unitLwt.t)``->serverLwt.t
establish_server_with_client_socket listen_address f creates a server
which listens for incoming connections on listen_address. When a
client makes a new connection, it is passed to f: more precisely, the
server calls
f client_address client_socketwhere client_address is the address (peer name) of the new client, and
client_socket is the socket connected to the client.
The server does not block waiting for f to complete: it concurrently
tries to accept more client connections while f is handling the
client.
When the promise returned by f completes (i.e., f is done handling
the client), establish_server_with_client_socket automatically closes
client_socket. This is a default behavior that is useful for simple
cases, but for a robust application you should explicitly close these
channels yourself, and handle any exceptions as appropriate. If the
channels are still open when f completes, and their automatic closing
raises an exception, establish_server_with_client_socket treats it as
an unhandled exception reaching the top level of the application: it
passes that exception to
Lwt.async_exception_hook, the
default behavior of which is to print the exception and terminate your
process.
Automatic closing can be completely disabled by passing
~no_close:true.
Similarly, if f raises an exception (or the promise it returns fails
with an exception), establish_server_with_client_socket can do nothing
with that exception, except pass it to
Lwt.async_exception_hook.
~server_fd can be specified to use an existing file descriptor for
listening. Otherwise, a fresh socket is created internally. In either
case, establish_server_with_client_socket will internally assign
listen_address to the server socket.
~backlog is the argument passed to
Lwt_unix.listen. Its default value is
SOMAXCONN, which varies by platform and socket kind.
The returned promise (a server Lwt.t) resolves when the server has
just started listening on listen_address: right after the internal
call to listen, and right before the first internal call to accept.
- since 4.1.0
valestablish_server_with_client_address : ``?fd:Lwt_unix.file_descr->``?buffer_size:int->``?backlog:int->``?no_close:bool->Unix.sockaddr->``(Lwt_unix.sockaddr->``(input_channel*output_channel)``->``unitLwt.t)``->serverLwt.t
Like
Lwt_io.establish_server_with_client_socket,
but passes two buffered channels to the connection handler f. These
channels wrap the client socket.
The channels are closed automatically when the promise returned by f
resolves. To avoid this behavior, pass ~no_close:true.
- since 3.1.0
Closes the given server's listening socket. The returned promise
resolves when the close(2) system call completes. This function does
not affect the sockets of connections that have already been accepted,
i.e. passed to f by establish_server.
- since 3.0.0
vallines_of_file :file_name->``stringLwt_stream.t
lines_of_file name returns a stream of all lines of the file with name
name. The file is automatically closed when all lines have been read.
vallines_to_file :file_name->``stringLwt_stream.t->``unitLwt.t
lines_to_file name lines writes all lines of lines to file with name
name.
valchars_of_file :file_name->``charLwt_stream.t
chars_of_file name returns a stream of all characters of the file with
name name. As for lines_of_file the file is
closed when all characters have been read.
valchars_to_file :file_name->``charLwt_stream.t->``unitLwt.t
chars_to_file name chars writes all characters of chars to name
Input/output of integers
moduletypeNumberIO=sig...end
Common interface for reading/writing integers in binary
Reading/writing of numbers in the system endianness.
include NumberIO
Reading
valread_int :input_channel->``intLwt.t
Reads a 32-bits integer as an ocaml int
valread_int16 :input_channel->``intLwt.t
valread_int32 :input_channel->``int32Lwt.t
valread_int64 :input_channel->``int64Lwt.t
valread_float32 :input_channel->``floatLwt.t
Reads an IEEE single precision floating point value
valread_float64 :input_channel->``floatLwt.t
Reads an IEEE double precision floating point value
Writing
valwrite_int :output_channel->``int->``unitLwt.t
Writes an ocaml int as a 32-bits integer
valwrite_int16 :output_channel->``int->``unitLwt.t
valwrite_int32 :output_channel->``int32->``unitLwt.t
valwrite_int64 :output_channel->``int64->``unitLwt.t
valwrite_float32 :output_channel->``float->``unitLwt.t
Writes an IEEE single precision floating point value
valwrite_float64 :output_channel->``float->``unitLwt.t
Writes an IEEE double precision floating point value
typebyte_order`` =Lwt_sys.byte_order=
|Little_endian
|Big_endian(* Type of byte order
*)
valsystem_byte_order :byte_order
Same as Lwt_sys.byte_order.
Low-level access to the internal buffer
valblock :'achannel->``int->``(Lwt_bytes.t->``int->'bLwt.t)``->'bLwt.t
block ch size f pass to f the internal buffer and an offset. The
buffer contains size chars at offset. f may read or write these
chars. size must satisfy 0 <= size <= 16
typedirect_access`` = ``{
da_buffer :Lwt_bytes.t;(* The internal buffer
*)
mutableda_ptr : int;(* The pointer to:
- the beginning of free space for output channels
- the beginning of data for input channels
*)
mutableda_max : int;(* The maximum offset
*)
da_perform : ``unit->``intLwt.t;(*
- for input channels: refills the buffer and returns how many bytes have been read
- for output channels: flush partially the buffer and returns how many bytes have been written
*)
}
Information for directly accessing the internal buffer of a channel
valdirect_access :'achannel->``(direct_access->'bLwt.t)``->'bLwt.t
direct_access ch f passes to f a
direct_access structure. f must use it and
update da_ptr to reflect how many bytes have been read/written.
Misc
valdefault_buffer_size : ``unit->int
Return the default size for buffers. Channels that are created without a specific buffer use new buffer of this size.
valset_default_buffer_size : ``int->unit
Change the default buffer size.
- 
raises Invalid_argument if the given size is smaller than 16or greater thanStdlib.Sys.max_string_length
Deprecated
valestablish_server : ``?fd:Lwt_unix.file_descr->``?buffer_size:int->``?backlog:int->``?no_close:bool->Unix.sockaddr->``(``(input_channel*output_channel)``->``unitLwt.t)``->serverLwt.t
Like establish_server_with_client_address, but does not pass the
client address or fd to the callback f.
- 
deprecated 
- 
since 3.0.0 
moduleVersioned:sig...end
Versioned variants of APIs undergoing breaking changes.
