1(**************************************************************************) 2(* *) 3(* OCaml *) 4(* *) 5(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) 6(* *) 7(* Copyright 1996 Institut National de Recherche en Informatique et *) 8(* en Automatique. *) 9(* *) 10(* All rights reserved. This file is distributed under the terms of *) 11(* the GNU Lesser General Public License version 2.1, with the *) 12(* special exception on linking described in the file LICENSE. *) 13(* *) 14(**************************************************************************) 15 16(** Interface to the Unix system. 17 18 Note: all the functions of this module (except {!error_message} and 19 {!handle_unix_error}) are liable to raise the {!Unix_error} 20 exception whenever the underlying system call signals an error. *) 21 22 23(** {6 Error report} *) 24 25 26type error = 27 E2BIG (** Argument list too long *) 28 | EACCES (** Permission denied *) 29 | EAGAIN (** Resource temporarily unavailable; try again *) 30 | EBADF (** Bad file descriptor *) 31 | EBUSY (** Resource unavailable *) 32 | ECHILD (** No child process *) 33 | EDEADLK (** Resource deadlock would occur *) 34 | EDOM (** Domain error for math functions, etc. *) 35 | EEXIST (** File exists *) 36 | EFAULT (** Bad address *) 37 | EFBIG (** File too large *) 38 | EINTR (** Function interrupted by signal *) 39 | EINVAL (** Invalid argument *) 40 | EIO (** Hardware I/O error *) 41 | EISDIR (** Is a directory *) 42 | EMFILE (** Too many open files by the process *) 43 | EMLINK (** Too many links *) 44 | ENAMETOOLONG (** Filename too long *) 45 | ENFILE (** Too many open files in the system *) 46 | ENODEV (** No such device *) 47 | ENOENT (** No such file or directory *) 48 | ENOEXEC (** Not an executable file *) 49 | ENOLCK (** No locks available *) 50 | ENOMEM (** Not enough memory *) 51 | ENOSPC (** No space left on device *) 52 | ENOSYS (** Function not supported *) 53 | ENOTDIR (** Not a directory *) 54 | ENOTEMPTY (** Directory not empty *) 55 | ENOTTY (** Inappropriate I/O control operation *) 56 | ENXIO (** No such device or address *) 57 | EPERM (** Operation not permitted *) 58 | EPIPE (** Broken pipe *) 59 | ERANGE (** Result too large *) 60 | EROFS (** Read-only file system *) 61 | ESPIPE (** Invalid seek e.g. on a pipe *) 62 | ESRCH (** No such process *) 63 | EXDEV (** Invalid link *) 64 | EWOULDBLOCK (** Operation would block *) 65 | EINPROGRESS (** Operation now in progress *) 66 | EALREADY (** Operation already in progress *) 67 | ENOTSOCK (** Socket operation on non-socket *) 68 | EDESTADDRREQ (** Destination address required *) 69 | EMSGSIZE (** Message too long *) 70 | EPROTOTYPE (** Protocol wrong type for socket *) 71 | ENOPROTOOPT (** Protocol not available *) 72 | EPROTONOSUPPORT (** Protocol not supported *) 73 | ESOCKTNOSUPPORT (** Socket type not supported *) 74 | EOPNOTSUPP (** Operation not supported on socket *) 75 | EPFNOSUPPORT (** Protocol family not supported *) 76 | EAFNOSUPPORT (** Address family not supported by protocol family *) 77 | EADDRINUSE (** Address already in use *) 78 | EADDRNOTAVAIL (** Can't assign requested address *) 79 | ENETDOWN (** Network is down *) 80 | ENETUNREACH (** Network is unreachable *) 81 | ENETRESET (** Network dropped connection on reset *) 82 | ECONNABORTED (** Software caused connection abort *) 83 | ECONNRESET (** Connection reset by peer *) 84 | ENOBUFS (** No buffer space available *) 85 | EISCONN (** Socket is already connected *) 86 | ENOTCONN (** Socket is not connected *) 87 | ESHUTDOWN (** Can't send after socket shutdown *) 88 | ETOOMANYREFS (** Too many references: can't splice *) 89 | ETIMEDOUT (** Connection timed out *) 90 | ECONNREFUSED (** Connection refused *) 91 | EHOSTDOWN (** Host is down *) 92 | EHOSTUNREACH (** No route to host *) 93 | ELOOP (** Too many levels of symbolic links *) 94 | EOVERFLOW (** File size or position not representable *) 95 96 | EUNKNOWNERR of int (** Unknown error *) 97(** The type of error codes. 98 Errors defined in the POSIX standard 99 and additional errors from UNIX98 and BSD. 100 All other errors are mapped to EUNKNOWNERR. 101*) 102 103 104exception Unix_error of error * string * string 105(** Raised by the system calls below when an error is encountered. 106 The first component is the error code; the second component 107 is the function name; the third component is the string parameter 108 to the function, if it has one, or the empty string otherwise. *) 109 110val error_message : error -> string 111(** Return a string describing the given error code. *) 112 113val handle_unix_error : ('a -> 'b) -> 'a -> 'b 114(** [handle_unix_error f x] applies [f] to [x] and returns the result. 115 If the exception {!Unix_error} is raised, it prints a message 116 describing the error and exits with code 2. *) 117 118 119(** {6 Access to the process environment} *) 120 121 122val environment : unit -> string array 123(** Return the process environment, as an array of strings 124 with the format ``variable=value''. *) 125 126val getenv : string -> string 127(** Return the value associated to a variable in the process 128 environment, unless the process has special privileges. 129 @raise Not_found if the variable is unbound or the process has 130 special privileges. 131 132 (This function is identical to {!Sys.getenv}. *) 133 134(* 135val unsafe_getenv : string -> string 136(** Return the value associated to a variable in the process 137 environment. 138 139 Unlike {!getenv}, this function returns the value even if the 140 process has special privileges. It is considered unsafe because the 141 programmer of a setuid or setgid program must be careful to avoid 142 using maliciously crafted environment variables in the search path 143 for executables, the locations for temporary files or logs, and the 144 like. 145 146 @raise Not_found if the variable is unbound. *) 147*) 148 149val putenv : string -> string -> unit 150(** [Unix.putenv name value] sets the value associated to a 151 variable in the process environment. 152 [name] is the name of the environment variable, 153 and [value] its new associated value. *) 154 155 156(** {6 Process handling} *) 157 158 159type process_status = 160 WEXITED of int 161 (** The process terminated normally by [exit]; 162 the argument is the return code. *) 163 | WSIGNALED of int 164 (** The process was killed by a signal; 165 the argument is the signal number. *) 166 | WSTOPPED of int 167 (** The process was stopped by a signal; the argument is the 168 signal number. *) 169(** The termination status of a process. See module {!Sys} for the 170 definitions of the standard signal numbers. Note that they are 171 not the numbers used by the OS. *) 172 173 174type wait_flag = 175 WNOHANG (** Do not block if no child has 176 died yet, but immediately return with a pid equal to 0.*) 177 | WUNTRACED (** Report also the children that receive stop signals. *) 178(** Flags for {!Unix.waitpid}. *) 179 180val execv : string -> string array -> 'a 181(** [execv prog args] execute the program in file [prog], with 182 the arguments [args], and the current process environment. 183 These [execv*] functions never return: on success, the current 184 program is replaced by the new one. 185 @raise Unix.Unix_error on failure. *) 186 187val execve : string -> string array -> string array -> 'a 188(** Same as {!Unix.execv}, except that the third argument provides the 189 environment to the program executed. *) 190 191val execvp : string -> string array -> 'a 192(** Same as {!Unix.execv}, except that 193 the program is searched in the path. *) 194 195val execvpe : string -> string array -> string array -> 'a 196(** Same as {!Unix.execve}, except that 197 the program is searched in the path. *) 198 199val fork : unit -> int 200(** Fork a new process. The returned integer is 0 for the child 201 process, the pid of the child process for the parent process. 202 203 On Windows: not implemented, use {!create_process} or threads. *) 204 205val wait : unit -> int * process_status 206(** Wait until one of the children processes die, and return its pid 207 and termination status. 208 209 On Windows: Not implemented, use {!waitpid}. *) 210 211val waitpid : wait_flag list -> int -> int * process_status 212(** Same as {!Unix.wait}, but waits for the child process whose pid is given. 213 A pid of [-1] means wait for any child. 214 A pid of [0] means wait for any child in the same process group 215 as the current process. 216 Negative pid arguments represent process groups. 217 The list of options indicates whether [waitpid] should return 218 immediately without waiting, and whether it should report stopped 219 children. 220 221 On Windows, this function can only wait for a given PID, not any 222 child process. *) 223 224val system : string -> process_status 225(** Execute the given command, wait until it terminates, and return 226 its termination status. The string is interpreted by the shell 227 [/bin/sh] (or the command interpreter [cmd.exe] on Windows) and 228 therefore can contain redirections, quotes, variables, etc. The 229 result [WEXITED 127] indicates that the shell couldn't be 230 executed. *) 231 232val getpid : unit -> int 233(** Return the pid of the process. *) 234 235val getppid : unit -> int 236(** Return the pid of the parent process. 237 On Windows: not implemented (because it is meaningless). *) 238 239val nice : int -> int 240(** Change the process priority. The integer argument is added to the 241 ``nice'' value. (Higher values of the ``nice'' value mean 242 lower priorities.) Return the new nice value. 243 244 On Windows: not implemented. *) 245 246 247(** {6 Basic file input/output} *) 248 249 250type file_descr 251(** The abstract type of file descriptors. *) 252 253val stdin : file_descr 254(** File descriptor for standard input.*) 255 256val stdout : file_descr 257(** File descriptor for standard output.*) 258 259val stderr : file_descr 260(** File descriptor for standard error. *) 261 262type open_flag = 263 O_RDONLY (** Open for reading *) 264 | O_WRONLY (** Open for writing *) 265 | O_RDWR (** Open for reading and writing *) 266 | O_NONBLOCK (** Open in non-blocking mode *) 267 | O_APPEND (** Open for append *) 268 | O_CREAT (** Create if nonexistent *) 269 | O_TRUNC (** Truncate to 0 length if existing *) 270 | O_EXCL (** Fail if existing *) 271 | O_NOCTTY (** Don't make this dev a controlling tty *) 272 | O_DSYNC (** Writes complete as `Synchronised I/O data 273 integrity completion' *) 274 | O_SYNC (** Writes complete as `Synchronised I/O file 275 integrity completion' *) 276 | O_RSYNC (** Reads complete as writes (depending on 277 O_SYNC/O_DSYNC) *) 278 | O_SHARE_DELETE (** Windows only: allow the file to be deleted 279 while still open *) 280 | O_CLOEXEC (** Set the close-on-exec flag on the 281 descriptor returned by {!openfile}. 282 See {!set_close_on_exec} for more 283 information. *) 284 | O_KEEPEXEC (** Clear the close-on-exec flag. 285 This is currently the default. *) 286(** The flags to {!Unix.openfile}. *) 287 288 289type file_perm = int 290(** The type of file access rights, e.g. [0o640] is read and write for user, 291 read for group, none for others *) 292 293val openfile : string -> open_flag list -> file_perm -> file_descr 294(** Open the named file with the given flags. Third argument is the 295 permissions to give to the file if it is created (see 296 {!umask}). Return a file descriptor on the named file. *) 297 298val close : file_descr -> unit 299(** Close a file descriptor. *) 300 301val read : file_descr -> bytes -> int -> int -> int 302(** [read fd buff ofs len] reads [len] bytes from descriptor [fd], 303 storing them in byte sequence [buff], starting at position [ofs] in 304 [buff]. Return the number of bytes actually read. *) 305 306val write : file_descr -> bytes -> int -> int -> int 307(** [write fd buff ofs len] writes [len] bytes to descriptor [fd], 308 taking them from byte sequence [buff], starting at position [ofs] 309 in [buff]. Return the number of bytes actually written. [write] 310 repeats the writing operation until all bytes have been written or 311 an error occurs. *) 312 313val single_write : file_descr -> bytes -> int -> int -> int 314(** Same as [write], but attempts to write only once. 315 Thus, if an error occurs, [single_write] guarantees that no data 316 has been written. *) 317 318val write_substring : file_descr -> string -> int -> int -> int 319(** Same as [write], but take the data from a string instead of a byte 320 sequence. 321 @since 4.02.0 *) 322 323val single_write_substring : file_descr -> string -> int -> int -> int 324(** Same as [single_write], but take the data from a string instead of 325 a byte sequence. 326 @since 4.02.0 *) 327 328(** {6 Interfacing with the standard input/output library} *) 329 330 331 332val in_channel_of_descr : file_descr -> in_channel 333(** Create an input channel reading from the given descriptor. 334 The channel is initially in binary mode; use 335 [set_binary_mode_in ic false] if text mode is desired. 336 Text mode is supported only if the descriptor refers to a file 337 or pipe, but is not supported if it refers to a socket. 338 On Windows, [set_binary_mode_in] always fails on channels created 339 with this function. 340 341 Beware that channels are buffered so more characters may have been 342 read from the file descriptor than those accessed using channel functions. 343 Channels also keep a copy of the current position in the file. 344 345 You need to explicitly close all channels created with this function. 346 Closing the channel also closes the underlying file descriptor (unless 347 it was already closed). *) 348 349val out_channel_of_descr : file_descr -> out_channel 350(** Create an output channel writing on the given descriptor. 351 The channel is initially in binary mode; use 352 [set_binary_mode_out oc false] if text mode is desired. 353 Text mode is supported only if the descriptor refers to a file 354 or pipe, but is not supported if it refers to a socket. 355 On Windows, [set_binary_mode_out] always fails on channels created 356 with this function. 357 358 Beware that channels are buffered so you may have to [flush] them 359 to ensure that all data has been sent to the file descriptor. 360 Channels also keep a copy of the current position in the file. 361 362 You need to explicitly close all channels created with this function. 363 Closing the channel flushes the data and closes the underlying file 364 descriptor (unless it has already been closed, in which case the 365 buffered data is lost).*) 366 367val descr_of_in_channel : in_channel -> file_descr 368(** Return the descriptor corresponding to an input channel. *) 369 370val descr_of_out_channel : out_channel -> file_descr 371(** Return the descriptor corresponding to an output channel. *) 372 373 374(** {6 Seeking and truncating} *) 375 376 377type seek_command = 378 SEEK_SET (** indicates positions relative to the beginning of the file *) 379 | SEEK_CUR (** indicates positions relative to the current position *) 380 | SEEK_END (** indicates positions relative to the end of the file *) 381(** Positioning modes for {!Unix.lseek}. *) 382 383 384val lseek : file_descr -> int -> seek_command -> int 385(** Set the current position for a file descriptor, and return the resulting 386 offset (from the beginning of the file). *) 387 388val truncate : string -> int -> unit 389(** Truncates the named file to the given size. 390 391 On Windows: not implemented. *) 392 393val ftruncate : file_descr -> int -> unit 394(** Truncates the file corresponding to the given descriptor 395 to the given size. 396 397 On Windows: not implemented. *) 398 399 400(** {6 File status} *) 401 402 403type file_kind = 404 S_REG (** Regular file *) 405 | S_DIR (** Directory *) 406 | S_CHR (** Character device *) 407 | S_BLK (** Block device *) 408 | S_LNK (** Symbolic link *) 409 | S_FIFO (** Named pipe *) 410 | S_SOCK (** Socket *) 411 412type stats = 413 { st_dev : int; (** Device number *) 414 st_ino : int; (** Inode number *) 415 st_kind : file_kind; (** Kind of the file *) 416 st_perm : file_perm; (** Access rights *) 417 st_nlink : int; (** Number of links *) 418 st_uid : int; (** User id of the owner *) 419 st_gid : int; (** Group ID of the file's group *) 420 st_rdev : int; (** Device minor number *) 421 st_size : int; (** Size in bytes *) 422 st_atime : float; (** Last access time *) 423 st_mtime : float; (** Last modification time *) 424 st_ctime : float; (** Last status change time *) 425 } 426(** The information returned by the {!Unix.stat} calls. *) 427 428val stat : string -> stats 429(** Return the information for the named file. *) 430 431val lstat : string -> stats 432(** Same as {!Unix.stat}, but in case the file is a symbolic link, 433 return the information for the link itself. *) 434 435val fstat : file_descr -> stats 436(** Return the information for the file associated with the given 437 descriptor. *) 438 439val isatty : file_descr -> bool 440(** Return [true] if the given file descriptor refers to a terminal or 441 console window, [false] otherwise. *) 442 443(** {6 File operations on large files} *) 444 445module LargeFile : 446 sig 447 val lseek : file_descr -> int64 -> seek_command -> int64 448 (** See {!Unix.lseek}. *) 449 450 val truncate : string -> int64 -> unit 451 (** See {!Unix.truncate}. *) 452 453 val ftruncate : file_descr -> int64 -> unit 454 (** See {!Unix.ftruncate}. *) 455 456 type stats = 457 { st_dev : int; (** Device number *) 458 st_ino : int; (** Inode number *) 459 st_kind : file_kind; (** Kind of the file *) 460 st_perm : file_perm; (** Access rights *) 461 st_nlink : int; (** Number of links *) 462 st_uid : int; (** User id of the owner *) 463 st_gid : int; (** Group ID of the file's group *) 464 st_rdev : int; (** Device minor number *) 465 st_size : int64; (** Size in bytes *) 466 st_atime : float; (** Last access time *) 467 st_mtime : float; (** Last modification time *) 468 st_ctime : float; (** Last status change time *) 469 } 470 val stat : string -> stats 471 val lstat : string -> stats 472 val fstat : file_descr -> stats 473 end 474(** File operations on large files. 475 This sub-module provides 64-bit variants of the functions 476 {!Unix.lseek} (for positioning a file descriptor), 477 {!Unix.truncate} and {!Unix.ftruncate} (for changing the size of a file), 478 and {!Unix.stat}, {!Unix.lstat} and {!Unix.fstat} (for obtaining 479 information on files). These alternate functions represent 480 positions and sizes by 64-bit integers (type [int64]) instead of 481 regular integers (type [int]), thus allowing operating on files 482 whose sizes are greater than [max_int]. *) 483 484(** {6 Operations on file names} *) 485 486 487val unlink : string -> unit 488(** Removes the named file. 489 490 If the named file is a directory, raises: 491 {ul 492 {- [EPERM] on POSIX compliant system} 493 {- [EISDIR] on Linux >= 2.1.132} 494 {- [EACCESS] on Windows}} 495*) 496 497val rename : string -> string -> unit 498(** [rename old new] changes the name of a file from [old] to [new]. *) 499 500val link : string -> string -> unit 501(** [link source dest] creates a hard link named [dest] to the file 502 named [source]. *) 503 504 505(** {6 File permissions and ownership} *) 506 507 508type access_permission = 509 R_OK (** Read permission *) 510 | W_OK (** Write permission *) 511 | X_OK (** Execution permission *) 512 | F_OK (** File exists *) 513(** Flags for the {!Unix.access} call. *) 514 515 516val chmod : string -> file_perm -> unit 517(** Change the permissions of the named file. *) 518 519val fchmod : file_descr -> file_perm -> unit 520(** Change the permissions of an opened file. 521 On Windows: not implemented. *) 522 523val chown : string -> int -> int -> unit 524(** Change the owner uid and owner gid of the named file. 525 On Windows: not implemented (make no sense on a DOS file system). *) 526 527val fchown : file_descr -> int -> int -> unit 528(** Change the owner uid and owner gid of an opened file. 529 On Windows: not implemented (make no sense on a DOS file system). *) 530 531val umask : int -> int 532(** Set the process's file mode creation mask, and return the previous 533 mask. 534 On Windows: not implemented. *) 535 536val access : string -> access_permission list -> unit 537(** Check that the process has the given permissions over the named file. 538 @raise Unix_error otherwise. 539 540 On Windows, execute permission [X_OK], cannot be tested, it just 541 tests for read permission instead. *) 542 543 544(** {6 Operations on file descriptors} *) 545 546 547val dup : ?cloexec:bool -> file_descr -> file_descr 548(** Return a new file descriptor referencing the same file as 549 the given descriptor. 550 See {!set_close_on_exec} for documentation on the [cloexec] 551 optional argument. *) 552 553val dup2 : ?cloexec:bool -> file_descr -> file_descr -> unit 554(** [dup2 fd1 fd2] duplicates [fd1] to [fd2], closing [fd2] if already 555 opened. 556 See {!set_close_on_exec} for documentation on the [cloexec] 557 optional argument. *) 558 559val set_nonblock : file_descr -> unit 560(** Set the ``non-blocking'' flag on the given descriptor. 561 When the non-blocking flag is set, reading on a descriptor 562 on which there is temporarily no data available raises the 563 [EAGAIN] or [EWOULDBLOCK] error instead of blocking; 564 writing on a descriptor on which there is temporarily no room 565 for writing also raises [EAGAIN] or [EWOULDBLOCK]. *) 566 567val clear_nonblock : file_descr -> unit 568(** Clear the ``non-blocking'' flag on the given descriptor. 569 See {!Unix.set_nonblock}.*) 570 571val set_close_on_exec : file_descr -> unit 572(** Set the ``close-on-exec'' flag on the given descriptor. 573 A descriptor with the close-on-exec flag is automatically 574 closed when the current process starts another program with 575 one of the [exec], [create_process] and [open_process] functions. 576 577 It is often a security hole to leak file descriptors opened on, say, 578 a private file to an external program: the program, then, gets access 579 to the private file and can do bad things with it. Hence, it is 580 highly recommended to set all file descriptors ``close-on-exec'', 581 except in the very few cases where a file descriptor actually needs 582 to be transmitted to another program. 583 584 The best way to set a file descriptor ``close-on-exec'' is to create 585 it in this state. To this end, the [openfile] function has 586 [O_CLOEXEC] and [O_KEEPEXEC] flags to enforce ``close-on-exec'' mode 587 or ``keep-on-exec'' mode, respectively. All other operations in 588 the Unix module that create file descriptors have an optional 589 argument [?cloexec:bool] to indicate whether the file descriptor 590 should be created in ``close-on-exec'' mode (by writing 591 [~cloexec:true]) or in ``keep-on-exec'' mode (by writing 592 [~cloexec:false]). For historical reasons, the default file 593 descriptor creation mode is ``keep-on-exec'', if no [cloexec] optional 594 argument is given. This is not a safe default, hence it is highly 595 recommended to pass explicit [cloexec] arguments to operations that 596 create file descriptors. 597 598 The [cloexec] optional arguments and the [O_KEEPEXEC] flag were introduced 599 in OCaml 4.05. Earlier, the common practice was to create file descriptors 600 in the default, ``keep-on-exec'' mode, then call [set_close_on_exec] 601 on those freshly-created file descriptors. This is not as safe as 602 creating the file descriptor in ``close-on-exec'' mode because, in 603 multithreaded programs, a window of vulnerability exists between the time 604 when the file descriptor is created and the time [set_close_on_exec] 605 completes. If another thread spawns another program during this window, 606 the descriptor will leak, as it is still in the ``keep-on-exec'' mode. 607 608 Regarding the atomicity guarantees given by [~cloexec:true] or by 609 the use of the [O_CLOEXEC] flag: on all platforms it is guaranteed 610 that a concurrently-executing Caml thread cannot leak the descriptor 611 by starting a new process. On Linux, this guarantee extends to 612 concurrently-executing C threads. As of Feb 2017, other operating 613 systems lack the necessary system calls and still expose a window 614 of vulnerability during which a C thread can see the newly-created 615 file descriptor in ``keep-on-exec'' mode. 616 *) 617 618val clear_close_on_exec : file_descr -> unit 619(** Clear the ``close-on-exec'' flag on the given descriptor. 620 See {!Unix.set_close_on_exec}.*) 621 622 623(** {6 Directories} *) 624 625 626val mkdir : string -> file_perm -> unit 627(** Create a directory with the given permissions (see {!umask}). *) 628 629val rmdir : string -> unit 630(** Remove an empty directory. *) 631 632val chdir : string -> unit 633(** Change the process working directory. *) 634 635val getcwd : unit -> string 636(** Return the name of the current working directory. *) 637 638val chroot : string -> unit 639(** Change the process root directory. 640 On Windows: not implemented. *) 641 642type dir_handle 643(** The type of descriptors over opened directories. *) 644 645val opendir : string -> dir_handle 646(** Open a descriptor on a directory *) 647 648val readdir : dir_handle -> string 649(** Return the next entry in a directory. 650 @raise End_of_file when the end of the directory has been reached. *) 651 652val rewinddir : dir_handle -> unit 653(** Reposition the descriptor to the beginning of the directory *) 654 655val closedir : dir_handle -> unit 656(** Close a directory descriptor. *) 657 658 659 660(** {6 Pipes and redirections} *) 661 662 663val pipe : ?cloexec:bool -> unit -> file_descr * file_descr 664(** Create a pipe. The first component of the result is opened 665 for reading, that's the exit to the pipe. The second component is 666 opened for writing, that's the entrance to the pipe. 667 See {!set_close_on_exec} for documentation on the [cloexec] 668 optional argument. *) 669 670val mkfifo : string -> file_perm -> unit 671(** Create a named pipe with the given permissions (see {!umask}). 672 On Windows: not implemented. *) 673 674 675(** {6 High-level process and redirection management} *) 676 677 678val create_process : 679 string -> string array -> file_descr -> file_descr -> file_descr -> int 680(** [create_process prog args new_stdin new_stdout new_stderr] 681 forks a new process that executes the program 682 in file [prog], with arguments [args]. The pid of the new 683 process is returned immediately; the new process executes 684 concurrently with the current process. 685 The standard input and outputs of the new process are connected 686 to the descriptors [new_stdin], [new_stdout] and [new_stderr]. 687 Passing e.g. [stdout] for [new_stdout] prevents the redirection 688 and causes the new process to have the same standard output 689 as the current process. 690 The executable file [prog] is searched in the path. 691 The new process has the same environment as the current process. *) 692 693val create_process_env : 694 string -> string array -> string array -> file_descr -> file_descr -> 695 file_descr -> int 696(** [create_process_env prog args env new_stdin new_stdout new_stderr] 697 works as {!Unix.create_process}, except that the extra argument 698 [env] specifies the environment passed to the program. *) 699 700 701val open_process_in : string -> in_channel 702(** High-level pipe and process management. This function 703 runs the given command in parallel with the program. 704 The standard output of the command is redirected to a pipe, 705 which can be read via the returned input channel. 706 The command is interpreted by the shell [/bin/sh] 707 (or [cmd.exe] on Windows), cf. [system]. *) 708 709val open_process_out : string -> out_channel 710(** Same as {!Unix.open_process_in}, but redirect the standard input of 711 the command to a pipe. Data written to the returned output channel 712 is sent to the standard input of the command. 713 Warning: writes on output channels are buffered, hence be careful 714 to call {!Pervasives.flush} at the right times to ensure 715 correct synchronization. *) 716 717val open_process : string -> in_channel * out_channel 718(** Same as {!Unix.open_process_out}, but redirects both the standard input 719 and standard output of the command to pipes connected to the two 720 returned channels. The input channel is connected to the output 721 of the command, and the output channel to the input of the command. *) 722 723val open_process_full : 724 string -> string array -> in_channel * out_channel * in_channel 725(** Similar to {!Unix.open_process}, but the second argument specifies 726 the environment passed to the command. The result is a triple 727 of channels connected respectively to the standard output, standard input, 728 and standard error of the command. *) 729 730val close_process_in : in_channel -> process_status 731(** Close channels opened by {!Unix.open_process_in}, 732 wait for the associated command to terminate, 733 and return its termination status. *) 734 735val close_process_out : out_channel -> process_status 736(** Close channels opened by {!Unix.open_process_out}, 737 wait for the associated command to terminate, 738 and return its termination status. *) 739 740val close_process : in_channel * out_channel -> process_status 741(** Close channels opened by {!Unix.open_process}, 742 wait for the associated command to terminate, 743 and return its termination status. *) 744 745val close_process_full : 746 in_channel * out_channel * in_channel -> process_status 747(** Close channels opened by {!Unix.open_process_full}, 748 wait for the associated command to terminate, 749 and return its termination status. *) 750 751 752(** {6 Symbolic links} *) 753 754 755val symlink : ?to_dir:bool -> string -> string -> unit 756(** [symlink ?to_dir source dest] creates the file [dest] as a symbolic link 757 to the file [source]. On Windows, [~to_dir] indicates if the symbolic link 758 points to a directory or a file; if omitted, [symlink] examines [source] 759 using [stat] and picks appropriately, if [source] does not exist then [false] 760 is assumed (for this reason, it is recommended that the [~to_dir] parameter 761 be specified in new code). On Unix, [~to_dir] is ignored. 762 763 Windows symbolic links are available in Windows Vista onwards. There are some 764 important differences between Windows symlinks and their POSIX counterparts. 765 766 Windows symbolic links come in two flavours: directory and regular, which 767 designate whether the symbolic link points to a directory or a file. The type 768 must be correct - a directory symlink which actually points to a file cannot 769 be selected with chdir and a file symlink which actually points to a 770 directory cannot be read or written (note that Cygwin's emulation layer 771 ignores this distinction). 772 773 When symbolic links are created to existing targets, this distinction doesn't 774 matter and [symlink] will automatically create the correct kind of symbolic 775 link. The distinction matters when a symbolic link is created to a 776 non-existent target. 777 778 The other caveat is that by default symbolic links are a privileged 779 operation. Administrators will always need to be running elevated (or with 780 UAC disabled) and by default normal user accounts need to be granted the 781 SeCreateSymbolicLinkPrivilege via Local Security Policy (secpol.msc) or via 782 Active Directory. 783 784 {!has_symlink} can be used to check that a process is able to create symbolic 785 links. *) 786 787val has_symlink : unit -> bool 788(** Returns [true] if the user is able to create symbolic links. On Windows, 789 this indicates that the user not only has the SeCreateSymbolicLinkPrivilege 790 but is also running elevated, if necessary. On other platforms, this is 791 simply indicates that the symlink system call is available. 792 @since 4.03.0 *) 793 794val readlink : string -> string 795(** Read the contents of a symbolic link. *) 796 797 798(** {6 Polling} *) 799 800 801val select : 802 file_descr list -> file_descr list -> file_descr list -> float -> 803 file_descr list * file_descr list * file_descr list 804(** Wait until some input/output operations become possible on 805 some channels. The three list arguments are, respectively, a set 806 of descriptors to check for reading (first argument), for writing 807 (second argument), or for exceptional conditions (third argument). 808 The fourth argument is the maximal timeout, in seconds; a 809 negative fourth argument means no timeout (unbounded wait). 810 The result is composed of three sets of descriptors: those ready 811 for reading (first component), ready for writing (second component), 812 and over which an exceptional condition is pending (third 813 component). *) 814 815 816(** {6 Locking} *) 817 818type lock_command = 819 F_ULOCK (** Unlock a region *) 820 | F_LOCK (** Lock a region for writing, and block if already locked *) 821 | F_TLOCK (** Lock a region for writing, or fail if already locked *) 822 | F_TEST (** Test a region for other process locks *) 823 | F_RLOCK (** Lock a region for reading, and block if already locked *) 824 | F_TRLOCK (** Lock a region for reading, or fail if already locked *) 825(** Commands for {!Unix.lockf}. *) 826 827val lockf : file_descr -> lock_command -> int -> unit 828(** [lockf fd cmd size] puts a lock on a region of the file opened 829 as [fd]. The region starts at the current read/write position for 830 [fd] (as set by {!Unix.lseek}), and extends [size] bytes forward if 831 [size] is positive, [size] bytes backwards if [size] is negative, 832 or to the end of the file if [size] is zero. 833 A write lock prevents any other 834 process from acquiring a read or write lock on the region. 835 A read lock prevents any other 836 process from acquiring a write lock on the region, but lets 837 other processes acquire read locks on it. 838 839 The [F_LOCK] and [F_TLOCK] commands attempts to put a write lock 840 on the specified region. 841 The [F_RLOCK] and [F_TRLOCK] commands attempts to put a read lock 842 on the specified region. 843 If one or several locks put by another process prevent the current process 844 from acquiring the lock, [F_LOCK] and [F_RLOCK] block until these locks 845 are removed, while [F_TLOCK] and [F_TRLOCK] fail immediately with an 846 exception. 847 The [F_ULOCK] removes whatever locks the current process has on 848 the specified region. 849 Finally, the [F_TEST] command tests whether a write lock can be 850 acquired on the specified region, without actually putting a lock. 851 It returns immediately if successful, or fails otherwise. 852 853 What happens when a process tries to lock a region of a file that is 854 already locked by the same process depends on the OS. On POSIX-compliant 855 systems, the second lock operation succeeds and may "promote" the older 856 lock from read lock to write lock. On Windows, the second lock 857 operation will block or fail. 858*) 859 860 861(** {6 Signals} 862 Note: installation of signal handlers is performed via 863 the functions {!Sys.signal} and {!Sys.set_signal}. 864*) 865 866val kill : int -> int -> unit 867(** [kill pid sig] sends signal number [sig] to the process 868 with id [pid]. On Windows, only the {!Sys.sigkill} signal 869 is emulated. *) 870 871type sigprocmask_command = 872 SIG_SETMASK 873 | SIG_BLOCK 874 | SIG_UNBLOCK 875 876val sigprocmask : sigprocmask_command -> int list -> int list 877(** [sigprocmask cmd sigs] changes the set of blocked signals. 878 If [cmd] is [SIG_SETMASK], blocked signals are set to those in 879 the list [sigs]. 880 If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to 881 the set of blocked signals. 882 If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed 883 from the set of blocked signals. 884 [sigprocmask] returns the set of previously blocked signals. 885 886 On Windows: not implemented (no inter-process signals on Windows). *) 887 888val sigpending : unit -> int list 889(** Return the set of blocked signals that are currently pending. 890 891 On Windows: not implemented (no inter-process signals on Windows). *) 892 893val sigsuspend : int list -> unit 894(** [sigsuspend sigs] atomically sets the blocked signals to [sigs] 895 and waits for a non-ignored, non-blocked signal to be delivered. 896 On return, the blocked signals are reset to their initial value. 897 898 On Windows: not implemented (no inter-process signals on Windows). *) 899 900val pause : unit -> unit 901(** Wait until a non-ignored, non-blocked signal is delivered. 902 903 On Windows: not implemented (no inter-process signals on Windows). *) 904 905 906(** {6 Time functions} *) 907 908 909type process_times = 910 { tms_utime : float; (** User time for the process *) 911 tms_stime : float; (** System time for the process *) 912 tms_cutime : float; (** User time for the children processes *) 913 tms_cstime : float; (** System time for the children processes *) 914 } 915(** The execution times (CPU times) of a process. *) 916 917type tm = 918 { tm_sec : int; (** Seconds 0..60 *) 919 tm_min : int; (** Minutes 0..59 *) 920 tm_hour : int; (** Hours 0..23 *) 921 tm_mday : int; (** Day of month 1..31 *) 922 tm_mon : int; (** Month of year 0..11 *) 923 tm_year : int; (** Year - 1900 *) 924 tm_wday : int; (** Day of week (Sunday is 0) *) 925 tm_yday : int; (** Day of year 0..365 *) 926 tm_isdst : bool; (** Daylight time savings in effect *) 927 } 928(** The type representing wallclock time and calendar date. *) 929 930 931val time : unit -> float 932(** Return the current time since 00:00:00 GMT, Jan. 1, 1970, 933 in seconds. *) 934 935val gettimeofday : unit -> float 936(** Same as {!Unix.time}, but with resolution better than 1 second. *) 937 938val gmtime : float -> tm 939(** Convert a time in seconds, as returned by {!Unix.time}, into a date and 940 a time. Assumes UTC (Coordinated Universal Time), also known as GMT. 941 To perform the inverse conversion, set the TZ environment variable 942 to "UTC", use {!mktime}, and then restore the original value of TZ. *) 943 944val localtime : float -> tm 945(** Convert a time in seconds, as returned by {!Unix.time}, into a date and 946 a time. Assumes the local time zone. 947 The function performing the inverse conversion is {!mktime}. *) 948 949val mktime : tm -> float * tm 950(** Convert a date and time, specified by the [tm] argument, into 951 a time in seconds, as returned by {!Unix.time}. The [tm_isdst], 952 [tm_wday] and [tm_yday] fields of [tm] are ignored. Also return a 953 normalized copy of the given [tm] record, with the [tm_wday], 954 [tm_yday], and [tm_isdst] fields recomputed from the other fields, 955 and the other fields normalized (so that, e.g., 40 October is 956 changed into 9 November). The [tm] argument is interpreted in the 957 local time zone. *) 958 959val alarm : int -> int 960(** Schedule a [SIGALRM] signal after the given number of seconds. 961 962 On Windows: not implemented. *) 963 964val sleep : int -> unit 965(** Stop execution for the given number of seconds. *) 966 967val sleepf : float -> unit 968(** Stop execution for the given number of seconds. Like [sleep], 969 but fractions of seconds are supported. 970 971 @since 4.03.0 *) 972 973val times : unit -> process_times 974(** Return the execution times of the process. 975 On Windows, it is partially implemented, will not report timings 976 for child processes. *) 977 978val utimes : string -> float -> float -> unit 979(** Set the last access time (second arg) and last modification time 980 (third arg) for a file. Times are expressed in seconds from 981 00:00:00 GMT, Jan. 1, 1970. If both times are [0.0], the access 982 and last modification times are both set to the current time. *) 983 984type interval_timer = 985 ITIMER_REAL 986 (** decrements in real time, and sends the signal [SIGALRM] when 987 expired.*) 988 | ITIMER_VIRTUAL 989 (** decrements in process virtual time, and sends [SIGVTALRM] 990 when expired. *) 991 | ITIMER_PROF 992 (** (for profiling) decrements both when the process 993 is running and when the system is running on behalf of the 994 process; it sends [SIGPROF] when expired. *) 995(** The three kinds of interval timers. *) 996 997type interval_timer_status = 998 { it_interval : float; (** Period *) 999 it_value : float; (** Current value of the timer *) 1000 } 1001(** The type describing the status of an interval timer *) 1002 1003val getitimer : interval_timer -> interval_timer_status 1004(** Return the current status of the given interval timer. 1005 1006 On Windows: not implemented. *) 1007 1008val setitimer : 1009 interval_timer -> interval_timer_status -> interval_timer_status 1010(** [setitimer t s] sets the interval timer [t] and returns 1011 its previous status. The [s] argument is interpreted as follows: 1012 [s.it_value], if nonzero, is the time to the next timer expiration; 1013 [s.it_interval], if nonzero, specifies a value to 1014 be used in reloading [it_value] when the timer expires. 1015 Setting [s.it_value] to zero disables the timer. 1016 Setting [s.it_interval] to zero causes the timer to be disabled 1017 after its next expiration. 1018 1019 On Windows: not implemented. *) 1020 1021 1022(** {6 User id, group id} *) 1023 1024 1025val getuid : unit -> int 1026(** Return the user id of the user executing the process. 1027 On Windows, always return [1]. *) 1028 1029val geteuid : unit -> int 1030(** Return the effective user id under which the process runs. 1031 On Windows, always return [1]. *) 1032 1033val setuid : int -> unit 1034(** Set the real user id and effective user id for the process. 1035 On Windows: not implemented. *) 1036 1037val getgid : unit -> int 1038(** Return the group id of the user executing the process. 1039 On Windows, always return [1]. *) 1040 1041val getegid : unit -> int 1042(** Return the effective group id under which the process runs. 1043 On Windows, always return [1]. *) 1044 1045val setgid : int -> unit 1046(** Set the real group id and effective group id for the process. 1047 On Windows: not implemented. *) 1048 1049val getgroups : unit -> int array 1050(** Return the list of groups to which the user executing the process 1051 belongs. 1052 On Windows, always return [[|1|]]. *) 1053 1054val setgroups : int array -> unit 1055(** [setgroups groups] sets the supplementary group IDs for the 1056 calling process. Appropriate privileges are required. 1057 On Windows: not implemented. *) 1058 1059val initgroups : string -> int -> unit 1060(** [initgroups user group] initializes the group access list by 1061 reading the group database /etc/group and using all groups of 1062 which [user] is a member. The additional group [group] is also 1063 added to the list. 1064 On Windows: not implemented. *) 1065 1066type passwd_entry = 1067 { pw_name : string; 1068 pw_passwd : string; 1069 pw_uid : int; 1070 pw_gid : int; 1071 pw_gecos : string; 1072 pw_dir : string; 1073 pw_shell : string 1074 } 1075(** Structure of entries in the [passwd] database. *) 1076 1077type group_entry = 1078 { gr_name : string; 1079 gr_passwd : string; 1080 gr_gid : int; 1081 gr_mem : string array 1082 } 1083(** Structure of entries in the [groups] database. *) 1084 1085val getlogin : unit -> string 1086(** Return the login name of the user executing the process. *) 1087 1088val getpwnam : string -> passwd_entry 1089(** Find an entry in [passwd] with the given name. 1090 @raise Not_found if no such entry exist. 1091 1092 On Windows, always raise [Not_found]. *) 1093 1094val getgrnam : string -> group_entry 1095(** Find an entry in [group] with the given name. 1096 @raise Not_found if no such entry exist. 1097 1098 On Windows, always raise [Not_found]. *) 1099 1100val getpwuid : int -> passwd_entry 1101(** Find an entry in [passwd] with the given user id. 1102 @raise Not_found if no such entry exist. 1103 1104 On Windows, always raise [Not_found]. *) 1105 1106val getgrgid : int -> group_entry 1107(** Find an entry in [group] with the given group id. 1108 @raise Not_found if no such entry exist. 1109 1110 On Windows, always raise [Not_found]. *) 1111 1112 1113(** {6 Internet addresses} *) 1114 1115 1116type inet_addr 1117(** The abstract type of Internet addresses. *) 1118 1119val inet_addr_of_string : string -> inet_addr 1120(** Conversion from the printable representation of an Internet 1121 address to its internal representation. The argument string 1122 consists of 4 numbers separated by periods ([XXX.YYY.ZZZ.TTT]) 1123 for IPv4 addresses, and up to 8 numbers separated by colons 1124 for IPv6 addresses. 1125 @raise Failure when given a string that does not match these formats. *) 1126 1127val string_of_inet_addr : inet_addr -> string 1128(** Return the printable representation of the given Internet address. 1129 See {!Unix.inet_addr_of_string} for a description of the 1130 printable representation. *) 1131 1132val inet_addr_any : inet_addr 1133(** A special IPv4 address, for use only with [bind], representing 1134 all the Internet addresses that the host machine possesses. *) 1135 1136val inet_addr_loopback : inet_addr 1137(** A special IPv4 address representing the host machine ([127.0.0.1]). *) 1138 1139val inet6_addr_any : inet_addr 1140(** A special IPv6 address, for use only with [bind], representing 1141 all the Internet addresses that the host machine possesses. *) 1142 1143val inet6_addr_loopback : inet_addr 1144(** A special IPv6 address representing the host machine ([::1]). *) 1145 1146 1147(** {6 Sockets} *) 1148 1149 1150type socket_domain = 1151 PF_UNIX (** Unix domain *) 1152 | PF_INET (** Internet domain (IPv4) *) 1153 | PF_INET6 (** Internet domain (IPv6) *) 1154(** The type of socket domains. Not all platforms support 1155 IPv6 sockets (type [PF_INET6]). Windows does not support 1156 [PF_UNIX]. *) 1157 1158type socket_type = 1159 SOCK_STREAM (** Stream socket *) 1160 | SOCK_DGRAM (** Datagram socket *) 1161 | SOCK_RAW (** Raw socket *) 1162 | SOCK_SEQPACKET (** Sequenced packets socket *) 1163(** The type of socket kinds, specifying the semantics of 1164 communications. [SOCK_SEQPACKET] is included for completeness, 1165 but is rarely supported by the OS, and needs system calls that 1166 are not available in this library. *) 1167 1168type sockaddr = 1169 ADDR_UNIX of string 1170 | ADDR_INET of inet_addr * int 1171(** The type of socket addresses. [ADDR_UNIX name] is a socket 1172 address in the Unix domain; [name] is a file name in the file 1173 system. [ADDR_INET(addr,port)] is a socket address in the Internet 1174 domain; [addr] is the Internet address of the machine, and 1175 [port] is the port number. *) 1176 1177val socket : 1178 ?cloexec:bool -> socket_domain -> socket_type -> int -> file_descr 1179(** Create a new socket in the given domain, and with the 1180 given kind. The third argument is the protocol type; 0 selects 1181 the default protocol for that kind of sockets. 1182 See {!set_close_on_exec} for documentation on the [cloexec] 1183 optional argument. *) 1184 1185val domain_of_sockaddr: sockaddr -> socket_domain 1186(** Return the socket domain adequate for the given socket address. *) 1187 1188val socketpair : 1189 ?cloexec:bool -> socket_domain -> socket_type -> int -> 1190 file_descr * file_descr 1191(** Create a pair of unnamed sockets, connected together. 1192 See {!set_close_on_exec} for documentation on the [cloexec] 1193 optional argument. *) 1194 1195val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr 1196(** Accept connections on the given socket. The returned descriptor 1197 is a socket connected to the client; the returned address is 1198 the address of the connecting client. 1199 See {!set_close_on_exec} for documentation on the [cloexec] 1200 optional argument. *) 1201 1202val bind : file_descr -> sockaddr -> unit 1203(** Bind a socket to an address. *) 1204 1205val connect : file_descr -> sockaddr -> unit 1206(** Connect a socket to an address. *) 1207 1208val listen : file_descr -> int -> unit 1209(** Set up a socket for receiving connection requests. The integer 1210 argument is the maximal number of pending requests. *) 1211 1212type shutdown_command = 1213 SHUTDOWN_RECEIVE (** Close for receiving *) 1214 | SHUTDOWN_SEND (** Close for sending *) 1215 | SHUTDOWN_ALL (** Close both *) 1216(** The type of commands for [shutdown]. *) 1217 1218 1219val shutdown : file_descr -> shutdown_command -> unit 1220(** Shutdown a socket connection. [SHUTDOWN_SEND] as second argument 1221 causes reads on the other end of the connection to return 1222 an end-of-file condition. 1223 [SHUTDOWN_RECEIVE] causes writes on the other end of the connection 1224 to return a closed pipe condition ([SIGPIPE] signal). *) 1225 1226val getsockname : file_descr -> sockaddr 1227(** Return the address of the given socket. *) 1228 1229val getpeername : file_descr -> sockaddr 1230(** Return the address of the host connected to the given socket. *) 1231 1232type msg_flag = 1233 MSG_OOB 1234 | MSG_DONTROUTE 1235 | MSG_PEEK 1236(** The flags for {!Unix.recv}, {!Unix.recvfrom}, 1237 {!Unix.send} and {!Unix.sendto}. *) 1238 1239val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int 1240(** Receive data from a connected socket. *) 1241 1242val recvfrom : 1243 file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr 1244(** Receive data from an unconnected socket. *) 1245 1246val send : file_descr -> bytes -> int -> int -> msg_flag list -> int 1247(** Send data over a connected socket. *) 1248 1249val send_substring : file_descr -> string -> int -> int -> msg_flag list -> int 1250(** Same as [send], but take the data from a string instead of a byte 1251 sequence. 1252 @since 4.02.0 *) 1253 1254val sendto : 1255 file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int 1256(** Send data over an unconnected socket. *) 1257 1258val sendto_substring : 1259 file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int 1260(** Same as [sendto], but take the data from a string instead of a 1261 byte sequence. 1262 @since 4.02.0 *) 1263 1264 1265(** {6 Socket options} *) 1266 1267 1268type socket_bool_option = 1269 SO_DEBUG (** Record debugging information *) 1270 | SO_BROADCAST (** Permit sending of broadcast messages *) 1271 | SO_REUSEADDR (** Allow reuse of local addresses for bind *) 1272 | SO_KEEPALIVE (** Keep connection active *) 1273 | SO_DONTROUTE (** Bypass the standard routing algorithms *) 1274 | SO_OOBINLINE (** Leave out-of-band data in line *) 1275 | SO_ACCEPTCONN (** Report whether socket listening is enabled *) 1276 | TCP_NODELAY (** Control the Nagle algorithm for TCP sockets *) 1277 | IPV6_ONLY (** Forbid binding an IPv6 socket to an IPv4 address *) 1278(** The socket options that can be consulted with {!Unix.getsockopt} 1279 and modified with {!Unix.setsockopt}. These options have a boolean 1280 ([true]/[false]) value. *) 1281 1282type socket_int_option = 1283 SO_SNDBUF (** Size of send buffer *) 1284 | SO_RCVBUF (** Size of received buffer *) 1285 | SO_ERROR (** Deprecated. Use {!Unix.getsockopt_error} instead. *) 1286 | SO_TYPE (** Report the socket type *) 1287 | SO_RCVLOWAT (** Minimum number of bytes to process for input operations*) 1288 | SO_SNDLOWAT (** Minimum number of bytes to process for output 1289 operations *) 1290(** The socket options that can be consulted with {!Unix.getsockopt_int} 1291 and modified with {!Unix.setsockopt_int}. These options have an 1292 integer value. *) 1293 1294type socket_optint_option = 1295 SO_LINGER (** Whether to linger on closed connections 1296 that have data present, and for how long 1297 (in seconds) *) 1298(** The socket options that can be consulted with {!Unix.getsockopt_optint} 1299 and modified with {!Unix.setsockopt_optint}. These options have a 1300 value of type [int option], with [None] meaning ``disabled''. *) 1301 1302type socket_float_option = 1303 SO_RCVTIMEO (** Timeout for input operations *) 1304 | SO_SNDTIMEO (** Timeout for output operations *) 1305(** The socket options that can be consulted with {!Unix.getsockopt_float} 1306 and modified with {!Unix.setsockopt_float}. These options have a 1307 floating-point value representing a time in seconds. 1308 The value 0 means infinite timeout. *) 1309 1310val getsockopt : file_descr -> socket_bool_option -> bool 1311(** Return the current status of a boolean-valued option 1312 in the given socket. *) 1313 1314val setsockopt : file_descr -> socket_bool_option -> bool -> unit 1315(** Set or clear a boolean-valued option in the given socket. *) 1316 1317val getsockopt_int : file_descr -> socket_int_option -> int 1318(** Same as {!Unix.getsockopt} for an integer-valued socket option. *) 1319 1320val setsockopt_int : file_descr -> socket_int_option -> int -> unit 1321(** Same as {!Unix.setsockopt} for an integer-valued socket option. *) 1322 1323val getsockopt_optint : file_descr -> socket_optint_option -> int option 1324(** Same as {!Unix.getsockopt} for a socket option whose value is an 1325 [int option]. *) 1326 1327val setsockopt_optint : 1328 file_descr -> socket_optint_option -> int option -> unit 1329(** Same as {!Unix.setsockopt} for a socket option whose value is an 1330 [int option]. *) 1331 1332val getsockopt_float : file_descr -> socket_float_option -> float 1333(** Same as {!Unix.getsockopt} for a socket option whose value is a 1334 floating-point number. *) 1335 1336val setsockopt_float : file_descr -> socket_float_option -> float -> unit 1337(** Same as {!Unix.setsockopt} for a socket option whose value is a 1338 floating-point number. *) 1339 1340val getsockopt_error : file_descr -> error option 1341(** Return the error condition associated with the given socket, 1342 and clear it. *) 1343 1344 1345(** {6 High-level network connection functions} *) 1346 1347 1348val open_connection : sockaddr -> in_channel * out_channel 1349(** Connect to a server at the given address. 1350 Return a pair of buffered channels connected to the server. 1351 Remember to call {!Pervasives.flush} on the output channel at the right 1352 times to ensure correct synchronization. *) 1353 1354val shutdown_connection : in_channel -> unit 1355(** ``Shut down'' a connection established with {!Unix.open_connection}; 1356 that is, transmit an end-of-file condition to the server reading 1357 on the other side of the connection. This does not fully close the 1358 file descriptor associated with the channel, which you must remember 1359 to free via {!Pervasives.close_in}. *) 1360 1361val establish_server : (in_channel -> out_channel -> unit) -> sockaddr -> unit 1362(** Establish a server on the given address. 1363 The function given as first argument is called for each connection 1364 with two buffered channels connected to the client. A new process 1365 is created for each connection. The function {!Unix.establish_server} 1366 never returns normally. 1367 1368 On Windows, it is not implemented. Use threads. *) 1369 1370 1371(** {6 Host and protocol databases} *) 1372 1373 1374type host_entry = 1375 { h_name : string; 1376 h_aliases : string array; 1377 h_addrtype : socket_domain; 1378 h_addr_list : inet_addr array 1379 } 1380(** Structure of entries in the [hosts] database. *) 1381 1382type protocol_entry = 1383 { p_name : string; 1384 p_aliases : string array; 1385 p_proto : int 1386 } 1387(** Structure of entries in the [protocols] database. *) 1388 1389type service_entry = 1390 { s_name : string; 1391 s_aliases : string array; 1392 s_port : int; 1393 s_proto : string 1394 } 1395(** Structure of entries in the [services] database. *) 1396 1397val gethostname : unit -> string 1398(** Return the name of the local host. *) 1399 1400val gethostbyname : string -> host_entry 1401(** Find an entry in [hosts] with the given name. 1402 @raise Not_found if no such entry exist. *) 1403 1404val gethostbyaddr : inet_addr -> host_entry 1405(** Find an entry in [hosts] with the given address. 1406 @raise Not_found if no such entry exist. *) 1407 1408val getprotobyname : string -> protocol_entry 1409(** Find an entry in [protocols] with the given name. 1410 @raise Not_found if no such entry exist. *) 1411 1412val getprotobynumber : int -> protocol_entry 1413(** Find an entry in [protocols] with the given protocol number. 1414 @raise Not_found if no such entry exist. *) 1415 1416val getservbyname : string -> string -> service_entry 1417(** Find an entry in [services] with the given name. 1418 @raise Not_found if no such entry exist. *) 1419 1420val getservbyport : int -> string -> service_entry 1421(** Find an entry in [services] with the given service number. 1422 @raise Not_found if no such entry exist. *) 1423 1424type addr_info = 1425 { ai_family : socket_domain; (** Socket domain *) 1426 ai_socktype : socket_type; (** Socket type *) 1427 ai_protocol : int; (** Socket protocol number *) 1428 ai_addr : sockaddr; (** Address *) 1429 ai_canonname : string (** Canonical host name *) 1430 } 1431(** Address information returned by {!Unix.getaddrinfo}. *) 1432 1433type getaddrinfo_option = 1434 AI_FAMILY of socket_domain (** Impose the given socket domain *) 1435 | AI_SOCKTYPE of socket_type (** Impose the given socket type *) 1436 | AI_PROTOCOL of int (** Impose the given protocol *) 1437 | AI_NUMERICHOST (** Do not call name resolver, 1438 expect numeric IP address *) 1439 | AI_CANONNAME (** Fill the [ai_canonname] field 1440 of the result *) 1441 | AI_PASSIVE (** Set address to ``any'' address 1442 for use with {!Unix.bind} *) 1443(** Options to {!Unix.getaddrinfo}. *) 1444 1445val getaddrinfo: 1446 string -> string -> getaddrinfo_option list -> addr_info list 1447(** [getaddrinfo host service opts] returns a list of {!Unix.addr_info} 1448 records describing socket parameters and addresses suitable for 1449 communicating with the given host and service. The empty list is 1450 returned if the host or service names are unknown, or the constraints 1451 expressed in [opts] cannot be satisfied. 1452 1453 [host] is either a host name or the string representation of an IP 1454 address. [host] can be given as the empty string; in this case, 1455 the ``any'' address or the ``loopback'' address are used, 1456 depending whether [opts] contains [AI_PASSIVE]. 1457 [service] is either a service name or the string representation of 1458 a port number. [service] can be given as the empty string; 1459 in this case, the port field of the returned addresses is set to 0. 1460 [opts] is a possibly empty list of options that allows the caller 1461 to force a particular socket domain (e.g. IPv6 only or IPv4 only) 1462 or a particular socket type (e.g. TCP only or UDP only). *) 1463 1464type name_info = 1465 { ni_hostname : string; (** Name or IP address of host *) 1466 ni_service : string; (** Name of service or port number *) 1467 } 1468(** Host and service information returned by {!Unix.getnameinfo}. *) 1469 1470type getnameinfo_option = 1471 NI_NOFQDN (** Do not qualify local host names *) 1472 | NI_NUMERICHOST (** Always return host as IP address *) 1473 | NI_NAMEREQD (** Fail if host name cannot be determined *) 1474 | NI_NUMERICSERV (** Always return service as port number *) 1475 | NI_DGRAM (** Consider the service as UDP-based 1476 instead of the default TCP *) 1477(** Options to {!Unix.getnameinfo}. *) 1478 1479val getnameinfo : sockaddr -> getnameinfo_option list -> name_info 1480(** [getnameinfo addr opts] returns the host name and service name 1481 corresponding to the socket address [addr]. [opts] is a possibly 1482 empty list of options that governs how these names are obtained. 1483 @raise Not_found if an error occurs. *) 1484 1485 1486(** {6 Terminal interface} *) 1487 1488 1489(** The following functions implement the POSIX standard terminal 1490 interface. They provide control over asynchronous communication ports 1491 and pseudo-terminals. Refer to the [termios] man page for a 1492 complete description. *) 1493 1494type terminal_io = 1495 { 1496 (* input modes *) 1497 mutable c_ignbrk : bool; (** Ignore the break condition. *) 1498 mutable c_brkint : bool; (** Signal interrupt on break condition. *) 1499 mutable c_ignpar : bool; (** Ignore characters with parity errors. *) 1500 mutable c_parmrk : bool; (** Mark parity errors. *) 1501 mutable c_inpck : bool; (** Enable parity check on input. *) 1502 mutable c_istrip : bool; (** Strip 8th bit on input characters. *) 1503 mutable c_inlcr : bool; (** Map NL to CR on input. *) 1504 mutable c_igncr : bool; (** Ignore CR on input. *) 1505 mutable c_icrnl : bool; (** Map CR to NL on input. *) 1506 mutable c_ixon : bool; (** Recognize XON/XOFF characters on input. *) 1507 mutable c_ixoff : bool; (** Emit XON/XOFF chars to control input flow. *) 1508 (* Output modes: *) 1509 mutable c_opost : bool; (** Enable output processing. *) 1510 (* Control modes: *) 1511 mutable c_obaud : int; (** Output baud rate (0 means close connection).*) 1512 mutable c_ibaud : int; (** Input baud rate. *) 1513 mutable c_csize : int; (** Number of bits per character (5-8). *) 1514 mutable c_cstopb : int; (** Number of stop bits (1-2). *) 1515 mutable c_cread : bool; (** Reception is enabled. *) 1516 mutable c_parenb : bool; (** Enable parity generation and detection. *) 1517 mutable c_parodd : bool; (** Specify odd parity instead of even. *) 1518 mutable c_hupcl : bool; (** Hang up on last close. *) 1519 mutable c_clocal : bool; (** Ignore modem status lines. *) 1520 (* Local modes: *) 1521 mutable c_isig : bool; (** Generate signal on INTR, QUIT, SUSP. *) 1522 mutable c_icanon : bool; (** Enable canonical processing 1523 (line buffering and editing) *) 1524 mutable c_noflsh : bool; (** Disable flush after INTR, QUIT, SUSP. *) 1525 mutable c_echo : bool; (** Echo input characters. *) 1526 mutable c_echoe : bool; (** Echo ERASE (to erase previous character). *) 1527 mutable c_echok : bool; (** Echo KILL (to erase the current line). *) 1528 mutable c_echonl : bool; (** Echo NL even if c_echo is not set. *) 1529 (* Control characters: *) 1530 mutable c_vintr : char; (** Interrupt character (usually ctrl-C). *) 1531 mutable c_vquit : char; (** Quit character (usually ctrl-\). *) 1532 mutable c_verase : char; (** Erase character (usually DEL or ctrl-H). *) 1533 mutable c_vkill : char; (** Kill line character (usually ctrl-U). *) 1534 mutable c_veof : char; (** End-of-file character (usually ctrl-D). *) 1535 mutable c_veol : char; (** Alternate end-of-line char. (usually none). *) 1536 mutable c_vmin : int; (** Minimum number of characters to read 1537 before the read request is satisfied. *) 1538 mutable c_vtime : int; (** Maximum read wait (in 0.1s units). *) 1539 mutable c_vstart : char; (** Start character (usually ctrl-Q). *) 1540 mutable c_vstop : char; (** Stop character (usually ctrl-S). *) 1541 } 1542 1543val tcgetattr : file_descr -> terminal_io 1544(** Return the status of the terminal referred to by the given 1545 file descriptor. 1546 On Windows, not implemented. *) 1547 1548type setattr_when = 1549 TCSANOW 1550 | TCSADRAIN 1551 | TCSAFLUSH 1552 1553val tcsetattr : file_descr -> setattr_when -> terminal_io -> unit 1554(** Set the status of the terminal referred to by the given 1555 file descriptor. The second argument indicates when the 1556 status change takes place: immediately ([TCSANOW]), 1557 when all pending output has been transmitted ([TCSADRAIN]), 1558 or after flushing all input that has been received but not 1559 read ([TCSAFLUSH]). [TCSADRAIN] is recommended when changing 1560 the output parameters; [TCSAFLUSH], when changing the input 1561 parameters. 1562 1563 On Windows, not implemented. *) 1564 1565val tcsendbreak : file_descr -> int -> unit 1566(** Send a break condition on the given file descriptor. 1567 The second argument is the duration of the break, in 0.1s units; 1568 0 means standard duration (0.25s). 1569 1570 On Windows, not implemented. *) 1571 1572val tcdrain : file_descr -> unit 1573(** Waits until all output written on the given file descriptor 1574 has been transmitted. 1575 1576 On Windows, not implemented. *) 1577 1578type flush_queue = 1579 TCIFLUSH 1580 | TCOFLUSH 1581 | TCIOFLUSH 1582 1583val tcflush : file_descr -> flush_queue -> unit 1584(** Discard data written on the given file descriptor but not yet 1585 transmitted, or data received but not yet read, depending on the 1586 second argument: [TCIFLUSH] flushes data received but not read, 1587 [TCOFLUSH] flushes data written but not transmitted, and 1588 [TCIOFLUSH] flushes both. 1589 1590 On Windows, not implemented. *) 1591 1592type flow_action = 1593 TCOOFF 1594 | TCOON 1595 | TCIOFF 1596 | TCION 1597 1598val tcflow : file_descr -> flow_action -> unit 1599(** Suspend or restart reception or transmission of data on 1600 the given file descriptor, depending on the second argument: 1601 [TCOOFF] suspends output, [TCOON] restarts output, 1602 [TCIOFF] transmits a STOP character to suspend input, 1603 and [TCION] transmits a START character to restart input. 1604 1605 On Windows, not implemented. *) 1606 1607val setsid : unit -> int 1608(** Put the calling process in a new session and detach it from 1609 its controlling terminal. 1610 1611 On Windows, not implemented. *) 1612