Module Lwt_io
Buffered byte channels
exceptionChannel_closed of stringException raised when a channel is closed. The parameter is a description of the channel.
Types
Well-known instances
val stdin : input_channelThe standard input, it reads data from
Lwt_unix.stdin
val stdout : output_channelThe standard output, it writes data to
Lwt_unix.stdout
val stderr : output_channelThe standard output for error messages, it writes data to
Lwt_unix.stderr
val zero : input_channelInputs which returns always
'\x00'
val null : output_channelOutput which drops everything
Channels creation/manipulation
val pipe : ?in_buffer:Lwt_bytes.t -> ?out_buffer:Lwt_bytes.t -> unit -> input_channel * output_channelpipe ?in_buffer ?out_buffer ()creates a pipe usingLwt_unix.pipeand makes two channels from the two returned file descriptors
val make : ?buffer:Lwt_bytes.t -> ?close:(unit -> unit Lwt.t) -> ?seek:(int64 -> Unix.seek_command -> int64 Lwt.t) -> mode:'mode mode -> (Lwt_bytes.t -> int -> int -> int Lwt.t) -> 'mode channelmake ?buffer ?close ~mode perform_iois 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 perform_io
is the read or write function. It is called when more input is needed or when the buffer need to be flushed.
val of_bytes : mode:'mode mode -> Lwt_bytes.t -> 'mode channelCreate a channel from a byte array. Reading/writing is done directly on the provided array.
val of_fd : ?buffer:Lwt_bytes.t -> ?close:(unit -> unit Lwt.t) -> mode:'mode mode -> Lwt_unix.file_descr -> 'mode channelof_fd ?buffer ?close ~mode fdcreates a channel from a file descriptor.- parameter close
defaults to closing the file descriptor.
val of_unix_fd : ?buffer:Lwt_bytes.t -> ?close:(unit -> unit Lwt.t) -> mode:'mode mode -> Unix.file_descr -> 'mode channelof_unix_fd ?buffer ?close ~mode fdis a short-hand for:of_fd ?buffer ?close (Lwt_unix.of_unix_file_descr fd)
val close : 'a channel -> unit Lwt.tclose chcloses the given channel. Ifchis an output channel, it performs all pending actions, flushes it and closes it. Ifchis an input channel, it just closes it immediately.closereturns the result of the close function of the channel. Multiple calls toclosewill return exactly the same value.Note: you cannot use
closeon channels obtained withatomic.
val abort : 'a channel -> unit Lwt.tabort chabort current operations and close the channel immediately.
val atomic : ('a channel -> 'b Lwt.t) -> 'a channel -> 'b Lwt.tatomic ftransforms a sequence of io operations into one single atomic io operation.Note:
- the channel passed to
fis invalid afterfterminates atomiccan be called inside anotheratomic
- the channel passed to
val file_length : string -> int64 Lwt.tRetrieves 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, _, _)).
val buffered : 'a channel -> intbuffered ocreturns the number of bytes in the buffer
val flush : output_channel -> unit Lwt.tflush ocperforms all pending writes onoc
val flush_all : unit -> unit Lwt.tflush_all ()flushes all open output channels
val buffer_size : 'a channel -> intReturns the size of the internal buffer.
val is_busy : 'a channel -> boolis_busy channelreturns 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.
val is_closed : 'a channel -> boolis_closed channelreturns whether the given channel is currently closed.- since
- 4.2.0
Random access
val position : 'a channel -> int64position chReturns the current position in the channel.
Reading
val read_char : input_channel -> char Lwt.tread_char icreads the next character ofic.- raises End_of_file
if the end of the file is reached
val read_char_opt : input_channel -> char option Lwt.tSame as
Lwt_io.read_char, but does not raiseEnd_of_fileon end of input
val read_chars : input_channel -> char Lwt_stream.tread_chars icreturns a stream holding all characters ofic
val read_line : input_channel -> string Lwt.tread_line icreads one complete line fromicand 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_fileis raised. If it is reached before reading an end of line but characters have already been read, they are returned.
val read_line_opt : input_channel -> string option Lwt.tSame as
read_linebut do not raiseEnd_of_fileon end of input.
val read_lines : input_channel -> string Lwt_stream.tread_lines icreturns a stream holding all lines ofic
val read : ?count:int -> input_channel -> string Lwt.tIf
~countis specified,read ~count icreads at most~countcharacters fromic. Note that fewer than~countcharacters can be read; check the size of the resulting string.readreturns""if the end of input is reached.If
~countis not specified,read icreads all bytes until the end of input.
val read_into : input_channel -> bytes -> int -> int -> int Lwt.tread_into ic buffer offset lengthreads up tolengthbytes, stores them inbufferat offsetoffset, and returns the number of bytes read.Note:
read_intodoes not raiseEnd_of_file, it returns a length of0instead.
val read_into_exactly : input_channel -> bytes -> int -> int -> unit Lwt.tread_into_exactly ic buffer offset lengthreads exactlylengthbytes and stores them inbufferat offsetoffset.- raises End_of_file
on end of input
val read_value : input_channel -> 'a Lwt.tread_value channelreads a marshaled value fromchannel; it corresponds to the standard library'sMarshal.from_channel. The corresponding writing function iswrite_value.Note that reading marshaled values is not, in general, type-safe. See the warning in the description of module
Marshalfor details. The short version is: if you read a value of one type, such asstring, when a value of another type, such asinthas actually been marshaled tochannel, you may get arbitrary behavior, including segmentation faults, access violations, security bugs, etc.
Writing
val write_char : output_channel -> char -> unit Lwt.twrite_char oc charwritescharonoc
val write_chars : output_channel -> char Lwt_stream.t -> unit Lwt.twrite_chars oc charswrites all characters ofcharsonoc
val write : output_channel -> string -> unit Lwt.twrite oc strwrites all characters ofstronoc
val write_line : output_channel -> string -> unit Lwt.twrite_line oc strwritesstronocfollowed by a new-line.
val write_lines : output_channel -> string Lwt_stream.t -> unit Lwt.twrite_lines oc lineswrites all lines oflinestooc
val write_from : output_channel -> bytes -> int -> int -> int Lwt.twrite_from oc buffer offset lengthwrites up tolengthbytes tooc, frombufferat offsetoffsetand returns the number of bytes actually written
val write_from_string : output_channel -> string -> int -> int -> int Lwt.tSee
write.
val write_from_exactly : output_channel -> bytes -> int -> int -> unit Lwt.twrite_from_exactly oc buffer offset lengthwrites alllengthbytes frombufferat offsetoffsettooc
val write_from_string_exactly : output_channel -> string -> int -> int -> unit Lwt.tSee
write_from_exactly.
val write_value : output_channel -> ?flags:Stdlib.Marshal.extern_flags list -> 'a -> unit Lwt.twrite_value channel ?flags vwritesvtochannelusing theMarshalmodule of the standard library. SeeMarshal.to_channelfor an explanation of?flags.The corresponding reading function is
read_value. See warnings about type safety in the description ofread_value.
Printing
val fprint : output_channel -> string -> unit Lwt.tval fprintl : output_channel -> string -> unit Lwt.tval fprintf : output_channel -> ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.flush channel.
val fprintlf : output_channel -> ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.flush channel.
val print : string -> unit Lwt.tval printl : string -> unit Lwt.tval printf : ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.(flush stdout).
val printlf : ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.(flush stdout).
val eprint : string -> unit Lwt.tval eprintl : string -> unit Lwt.tval eprintf : ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.(flush stderr).
val eprintlf : ('a, unit, string, unit Lwt.t) Stdlib.format4 -> 'a%!does nothing here. To flush the channel, useLwt_io.(flush stderr).
Utilities
val hexdump_stream : output_channel -> char Lwt_stream.t -> unit Lwt.thexdump_stream oc byte_streamproduces the same output as the commandhexdump -C.
val hexdump : output_channel -> string -> unit Lwt.thexdump oc str = hexdump_stream oc (Lwt_stream.of_string str)
File utilities
val open_file : ?buffer:Lwt_bytes.t -> ?flags:Unix.open_flag list -> ?perm:Unix.file_perm -> mode:'a mode -> file_name -> 'a channel Lwt.tLwt_io.open_file ~mode fileopens 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
~bufferis supplied, it is used as the I/O buffer.If
~flagsis supplied, the file is opened with the given flags (seeUnix.open_flag). Note that~flagsis used exactly as given. For example, opening a file with~flagsand~mode:Inputdoes not implicitly addO_RDONLY. So, you should includeO_RDONLYwhen opening for reading (~mode:Input), andO_WRONLYwhen opening for writing (~mode:Input). It is also recommended to includeO_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_filetruncates (clears) the file by default. If you would like to keep the pre-existing contents of the file, use the~flagsparameter to pass a custom flags list that does not includeUnix.O_TRUNC.- raises Unix.Unix_error
on error.
val with_file : ?buffer:Lwt_bytes.t -> ?flags:Unix.open_flag list -> ?perm:Unix.file_perm -> mode:'a mode -> file_name -> ('a channel -> 'b Lwt.t) -> 'b Lwt.tLwt_io.with_file ~mode filename fopens the given usingLwt_io.open_file, and passes the resulting channel tof.Lwt_io.with_fileensures that the channel is closed when the promise returned byfresolves, or iffraises an exception.See
Lwt_io.open_filefor a description of the arguments, warnings, and other notes.
val open_temp_file : ?buffer:Lwt_bytes.t -> ?flags:Unix.open_flag list -> ?perm:Unix.file_perm -> ?temp_dir:string -> ?prefix:string -> ?suffix:string -> unit -> (string * output_channel) Lwt.topen_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
?bufferand?permarguments are passed directly to an internal call toLwt_io.open_file.If not specified,
?flagsdefaults to[O_CREATE; O_EXCL; O_WRONLY; O_CLOEXEC]. If specified, the specified flags are used exactly. Note that these should typically contain at leastO_CREATandO_EXCL, otherwiseopen_temp_filemay open an existing file.?temp_dircan be used to choose the directory in which the file is created. For the current directory, useFilename.current_dir_name. If not specified, the directory is taken fromFilename.get_temp_dir_name, which is typically set to your system temporary file directory.?prefixhelps determine the name of the file. It will be the prefix concatenated with a random sequence of characters. If not specified,open_temp_fileuses some default prefix.?suffixis likeprefix, 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
val with_temp_file : ?buffer:Lwt_bytes.t -> ?flags:Unix.open_flag list -> ?perm:Unix.file_perm -> ?temp_dir:string -> ?prefix:string -> ?suffix:string -> ((string * output_channel) -> 'b Lwt.t) -> 'b Lwt.twith_temp_file fcallsopen_temp_file(), passing all optional arguments directly to it. It then attachesfto run after the file is created, passing the filename and output channel tof. When the promise returned byfis resolved,with_temp_filecloses the channel and deletes the temporary file by callingLwt_unix.unlink.- since
- 3.2.0
val create_temp_dir : ?perm:Unix.file_perm -> ?parent:string -> ?prefix:string -> ?suffix:string -> unit -> string Lwt.tCreates 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
~permis specified, the directory is created with the given permissions. The default permissions are0755.~parentis the directory in which the temporary directory is created. If not specified, the default value is the result ofFilename.get_temp_dir_name ().~prefixis prepended to the directory name, and~suffixis appended to it.- since
- 4.4.0
val with_temp_dir : ?perm:Unix.file_perm -> ?parent:string -> ?prefix:string -> ?suffix:string -> (string -> 'a Lwt.t) -> 'a Lwt.twith_temp_dir ffirst callscreate_temp_dir, forwarding all optional arguments to it. Once the temporary directory is created atpath,with_temp_dir fcallsf path. When the promise returned byf pathis resolved,with_temp_dir frecursively deletes the temporary directory and all its contents.- since
- 4.4.0
val open_connection : ?fd:Lwt_unix.file_descr -> ?in_buffer:Lwt_bytes.t -> ?out_buffer:Lwt_bytes.t -> Unix.sockaddr -> (input_channel * output_channel) Lwt.topen_connection ?fd ?in_buffer ?out_buffer addropens a connection to the given address and returns two channels for using it. Iffdis not specified, a fresh one will be used.The connection is completely closed when you close both channels.
- raises Unix.Unix_error
on error.
val with_connection : ?fd:Lwt_unix.file_descr -> ?in_buffer:Lwt_bytes.t -> ?out_buffer:Lwt_bytes.t -> Unix.sockaddr -> ((input_channel * output_channel) -> 'a Lwt.t) -> 'a Lwt.twith_connection ?fd ?in_buffer ?out_buffer addr fopens a connection to the given address and passes the channels tof
val establish_server_with_client_socket : ?server_fd:Lwt_unix.file_descr -> ?backlog:int -> ?no_close:bool -> Unix.sockaddr -> (Lwt_unix.sockaddr -> Lwt_unix.file_descr -> unit Lwt.t) -> server Lwt.testablish_server_with_client_socket listen_address fcreates a server which listens for incoming connections onlisten_address. When a client makes a new connection, it is passed tof: more precisely, the server callsf client_address client_socketwhere
client_addressis the address (peer name) of the new client, andclient_socketis the socket connected to the client.The server does not block waiting for
fto complete: it concurrently tries to accept more client connections whilefis handling the client.When the promise returned by
fcompletes (i.e.,fis done handling the client),establish_server_with_client_socketautomatically closesclient_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 whenfcompletes, and their automatic closing raises an exception,establish_server_with_client_sockettreats it as an unhandled exception reaching the top level of the application: it passes that exception toLwt.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
fraises an exception (or the promise it returns fails with an exception),establish_server_with_client_socketcan do nothing with that exception, except pass it toLwt.async_exception_hook.~server_fdcan be specified to use an existing file descriptor for listening. Otherwise, a fresh socket is created internally. In either case,establish_server_with_client_socketwill internally assignlisten_addressto the server socket.~backlogis the argument passed toLwt_unix.listen. Its default value isSOMAXCONN, which varies by platform and socket kind.The returned promise (a
server Lwt.t) resolves when the server has just started listening onlisten_address: right after the internal call tolisten, and right before the first internal call toaccept.- since
- 4.1.0
val establish_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) -> unit Lwt.t) -> server Lwt.tLike
Lwt_io.establish_server_with_client_socket, but passes two buffered channels to the connection handlerf. These channels wrap the client socket.The channels are closed automatically when the promise returned by
fresolves. To avoid this behavior, pass~no_close:true.- since
- 3.1.0
val shutdown_server : server -> unit Lwt.tCloses 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 tofbyestablish_server.- since
- 3.0.0
val lines_of_file : file_name -> string Lwt_stream.tlines_of_file namereturns a stream of all lines of the file with namename. The file is automatically closed when all lines have been read.
val lines_to_file : file_name -> string Lwt_stream.t -> unit Lwt.tlines_to_file name lineswrites all lines oflinesto file with namename.
val chars_of_file : file_name -> char Lwt_stream.tchars_of_file namereturns a stream of all characters of the file with namename. As forlines_of_filethe file is closed when all characters have been read.
val chars_to_file : file_name -> char Lwt_stream.t -> unit Lwt.tchars_to_file name charswrites all characters ofcharstoname
Input/output of integers
module type NumberIO = sig ... endCommon interface for reading/writing integers in binary
Reading/writing of numbers in the system endianness.
include NumberIO
val read_int : input_channel -> int Lwt.tReads a 32-bits integer as an ocaml int
val read_int16 : input_channel -> int Lwt.tval read_int32 : input_channel -> int32 Lwt.tval read_int64 : input_channel -> int64 Lwt.tval read_float32 : input_channel -> float Lwt.tReads an IEEE single precision floating point value
val read_float64 : input_channel -> float Lwt.tReads an IEEE double precision floating point value
Writing
val write_int : output_channel -> int -> unit Lwt.tWrites an ocaml int as a 32-bits integer
val write_int16 : output_channel -> int -> unit Lwt.tval write_int32 : output_channel -> int32 -> unit Lwt.tval write_int64 : output_channel -> int64 -> unit Lwt.tval write_float32 : output_channel -> float -> unit Lwt.tWrites an IEEE single precision floating point value
val write_float64 : output_channel -> float -> unit Lwt.tWrites an IEEE double precision floating point value
type byte_order= Lwt_sys.byte_order=|Little_endian|Big_endianType of byte order
val system_byte_order : byte_orderSame as
Lwt_sys.byte_order.
Low-level access to the internal buffer
val block : 'a channel -> int -> (Lwt_bytes.t -> int -> 'b Lwt.t) -> 'b Lwt.tblock ch size fpass tofthe internal buffer and an offset. The buffer containssizechars atoffset.fmay read or write these chars.sizemust satisfy0 <= size <= 16
type direct_access={da_buffer : Lwt_bytes.t;The internal buffer
mutable da_ptr : int;The pointer to:
- the beginning of free space for output channels
- the beginning of data for input channels
mutable da_max : int;The maximum offset
da_perform : unit -> int Lwt.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
val direct_access : 'a channel -> (direct_access -> 'b Lwt.t) -> 'b Lwt.tdirect_access ch fpasses tofadirect_accessstructure.fmust use it and updateda_ptrto reflect how many bytes have been read/written.
Misc
Deprecated
val establish_server : ?fd:Lwt_unix.file_descr -> ?buffer_size:int -> ?backlog:int -> ?no_close:bool -> Unix.sockaddr -> ((input_channel * output_channel) -> unit Lwt.t) -> server Lwt.tLike
establish_server_with_client_address, but does not pass the client address or fd to the callbackf.- deprecated
- since
- 3.0.0
module Versioned : sig ... endVersioned variants of APIs undergoing breaking changes.