1Unix(3)                          OCaml library                         Unix(3)
2
3
4

NAME

6       Unix - Interface to the Unix system.
7

Module

9       Module   Unix
10

Documentation

12       Module Unix
13        : sig end
14
15
16       Interface to the Unix system.
17
18       Note:  all  the functions of this module (except Unix.error_message and
19       Unix.handle_unix_error ) are liable to raise the Unix.Unix_error excep‐
20       tion whenever the underlying system call signals an error.
21
22
23
24
25
26
27
28       === Error report ===
29
30
31       type error =
32        | E2BIG  (* Argument list too long
33        *)
34        | EACCES  (* Permission denied
35        *)
36        | EAGAIN  (* Resource temporarily unavailable; try again
37        *)
38        | EBADF  (* Bad file descriptor
39        *)
40        | EBUSY  (* Resource unavailable
41        *)
42        | ECHILD  (* No child process
43        *)
44        | EDEADLK  (* Resource deadlock would occur
45        *)
46        | EDOM  (* Domain error for math functions, etc.
47        *)
48        | EEXIST  (* File exists
49        *)
50        | EFAULT  (* Bad address
51        *)
52        | EFBIG  (* File too large
53        *)
54        | EINTR  (* Function interrupted by signal
55        *)
56        | EINVAL  (* Invalid argument
57        *)
58        | EIO  (* Hardware I/O error
59        *)
60        | EISDIR  (* Is a directory
61        *)
62        | EMFILE  (* Too many open files by the process
63        *)
64        | EMLINK  (* Too many links
65        *)
66        | ENAMETOOLONG  (* Filename too long
67        *)
68        | ENFILE  (* Too many open files in the system
69        *)
70        | ENODEV  (* No such device
71        *)
72        | ENOENT  (* No such file or directory
73        *)
74        | ENOEXEC  (* Not an executable file
75        *)
76        | ENOLCK  (* No locks available
77        *)
78        | ENOMEM  (* Not enough memory
79        *)
80        | ENOSPC  (* No space left on device
81        *)
82        | ENOSYS  (* Function not supported
83        *)
84        | ENOTDIR  (* Not a directory
85        *)
86        | ENOTEMPTY  (* Directory not empty
87        *)
88        | ENOTTY  (* Inappropriate I/O control operation
89        *)
90        | ENXIO  (* No such device or address
91        *)
92        | EPERM  (* Operation not permitted
93        *)
94        | EPIPE  (* Broken pipe
95        *)
96        | ERANGE  (* Result too large
97        *)
98        | EROFS  (* Read-only file system
99        *)
100        | ESPIPE  (* Invalid seek e.g. on a pipe
101        *)
102        | ESRCH  (* No such process
103        *)
104        | EXDEV  (* Invalid link
105        *)
106        | EWOULDBLOCK  (* Operation would block
107        *)
108        | EINPROGRESS  (* Operation now in progress
109        *)
110        | EALREADY  (* Operation already in progress
111        *)
112        | ENOTSOCK  (* Socket operation on non-socket
113        *)
114        | EDESTADDRREQ  (* Destination address required
115        *)
116        | EMSGSIZE  (* Message too long
117        *)
118        | EPROTOTYPE  (* Protocol wrong type for socket
119        *)
120        | ENOPROTOOPT  (* Protocol not available
121        *)
122        | EPROTONOSUPPORT  (* Protocol not supported
123        *)
124        | ESOCKTNOSUPPORT  (* Socket type not supported
125        *)
126        | EOPNOTSUPP  (* Operation not supported on socket
127        *)
128        | EPFNOSUPPORT  (* Protocol family not supported
129        *)
130        | EAFNOSUPPORT  (* Address family not supported by protocol family
131        *)
132        | EADDRINUSE  (* Address already in use
133        *)
134        | EADDRNOTAVAIL  (* Can't assign requested address
135        *)
136        | ENETDOWN  (* Network is down
137        *)
138        | ENETUNREACH  (* Network is unreachable
139        *)
140        | ENETRESET  (* Network dropped connection on reset
141        *)
142        | ECONNABORTED  (* Software caused connection abort
143        *)
144        | ECONNRESET  (* Connection reset by peer
145        *)
146        | ENOBUFS  (* No buffer space available
147        *)
148        | EISCONN  (* Socket is already connected
149        *)
150        | ENOTCONN  (* Socket is not connected
151        *)
152        | ESHUTDOWN  (* Can't send after socket shutdown
153        *)
154        | ETOOMANYREFS  (* Too many references: can't splice
155        *)
156        | ETIMEDOUT  (* Connection timed out
157        *)
158        | ECONNREFUSED  (* Connection refused
159        *)
160        | EHOSTDOWN  (* Host is down
161        *)
162        | EHOSTUNREACH  (* No route to host
163        *)
164        | ELOOP  (* Too many levels of symbolic links
165        *)
166        | EOVERFLOW  (* File size or position not representable
167        *)
168        | EUNKNOWNERR of int
169         (* Unknown error
170        *)
171
172
173       The  type  of  error  codes.   Errors defined in the POSIX standard and
174       additional errors from UNIX98 and BSD.  All other errors are mapped  to
175       EUNKNOWNERR.
176
177
178
179       exception Unix_error of error * string * string
180
181
182       Raised  by  the  system  calls below when an error is encountered.  The
183       first component is the error code; the second component is the function
184       name;  the  third component is the string parameter to the function, if
185       it has one, or the empty string otherwise.
186
187
188
189       val error_message : error -> string
190
191       Return a string describing the given error code.
192
193
194
195       val handle_unix_error : ('a -> 'b) -> 'a -> 'b
196
197
198       handle_unix_error f x applies f to x and returns the  result.   If  the
199       exception Unix.Unix_error is raised, it prints a message describing the
200       error and exits with code 2.
201
202
203
204
205       === Access to the process environment ===
206
207
208       val environment : unit -> string array
209
210       Return the process environment, as an array of strings with the  format
211       ``variable=value''.   The  returned  array  is empty if the process has
212       special privileges.
213
214
215
216       val unsafe_environment : unit -> string array
217
218       Return the process environment, as an array of strings with the  format
219       ``variable=value''.   Unlike Unix.environment , this function returns a
220       populated array even if the process has special  privileges.   See  the
221       documentation for Unix.unsafe_getenv for more details.
222
223
224       Since 4.06.0
225
226
227
228       val getenv : string -> string
229
230       Return  the  value associated to a variable in the process environment,
231       unless the process has special privileges.
232
233
234       Raises Not_found if the variable is unbound or the process has  special
235       privileges.
236
237       (This function is identical to Sys.getenv .
238
239
240
241       val unsafe_getenv : string -> string
242
243       Return the value associated to a variable in the process environment.
244
245       Unlike  Unix.getenv  ,  this  function  returns  the  value even if the
246       process has special privileges. It is  considered  unsafe  because  the
247       programmer of a setuid or setgid program must be careful to avoid using
248       maliciously crafted environment variables in the search path  for  exe‐
249       cutables, the locations for temporary files or logs, and the like.
250
251
252       Since 4.06.0
253
254
255       Raises Not_found if the variable is unbound.
256
257
258
259       val putenv : string -> string -> unit
260
261
262       Unix.putenv  name  value sets the value associated to a variable in the
263       process environment.  name is the name of the environment variable, and
264       value its new associated value.
265
266
267
268
269       === Process handling ===
270
271
272       type process_status =
273        | WEXITED of int
274         (*  The  process  terminated  normally  by exit ; the argument is the
275       return code.
276        *)
277        | WSIGNALED of int
278         (* The process was killed by a signal; the  argument  is  the  signal
279       number.
280        *)
281        | WSTOPPED of int
282         (*  The  process  was stopped by a signal; the argument is the signal
283       number.
284        *)
285
286
287       The termination status of a process.  See module Sys  for  the  defini‐
288       tions  of the standard signal numbers.  Note that they are not the num‐
289       bers used by the OS.
290
291
292       type wait_flag =
293        | WNOHANG  (* Do not block if no child has died yet,  but  immediately
294       return with a pid equal to 0.
295        *)
296        | WUNTRACED  (* Report also the children that receive stop signals.
297        *)
298
299
300       Flags for Unix.waitpid .
301
302
303
304       val execv : string -> string array -> 'a
305
306
307       execv  prog  args execute the program in file prog , with the arguments
308       args , and the current process  environment.   These  execv*  functions
309       never  return:  on  success, the current program is replaced by the new
310       one.
311
312
313       Raises Unix.Unix_error on failure.
314
315
316
317       val execve : string -> string array -> string array -> 'a
318
319       Same as Unix.execv , except that the third argument provides the  envi‐
320       ronment to the program executed.
321
322
323
324       val execvp : string -> string array -> 'a
325
326       Same as Unix.execv , except that the program is searched in the path.
327
328
329
330       val execvpe : string -> string array -> string array -> 'a
331
332       Same as Unix.execve , except that the program is searched in the path.
333
334
335
336       val fork : unit -> int
337
338       Fork  a  new  process. The returned integer is 0 for the child process,
339       the pid of the child process for the parent process.
340
341       On Windows: not implemented, use Unix.create_process or threads.
342
343
344
345       val wait : unit -> int * process_status
346
347       Wait until one of the children processes die, and return  its  pid  and
348       termination status.
349
350       On Windows: Not implemented, use Unix.waitpid .
351
352
353
354       val waitpid : wait_flag list -> int -> int * process_status
355
356       Same as Unix.wait , but waits for the child process whose pid is given.
357       A pid of -1 means wait for any child.  A pid of 0 means  wait  for  any
358       child  in  the same process group as the current process.  Negative pid
359       arguments represent process groups.   The  list  of  options  indicates
360       whether  waitpid should return immediately without waiting, and whether
361       it should report stopped children.
362
363       On Windows, this function can only wait for a given PID, not any  child
364       process.
365
366
367
368       val system : string -> process_status
369
370       Execute  the  given  command,  wait until it terminates, and return its
371       termination status. The string is interpreted by the shell /bin/sh  (or
372       the  command  interpreter cmd.exe on Windows) and therefore can contain
373       redirections, quotes, variables, etc. The result WEXITED 127  indicates
374       that the shell couldn't be executed.
375
376
377
378       val getpid : unit -> int
379
380       Return the pid of the process.
381
382
383
384       val getppid : unit -> int
385
386       Return  the  pid  of  the  parent process.  On Windows: not implemented
387       (because it is meaningless).
388
389
390
391       val nice : int -> int
392
393       Change the process priority. The  integer  argument  is  added  to  the
394       ``nice'' value. (Higher values of the ``nice'' value mean lower priori‐
395       ties.) Return the new nice value.
396
397       On Windows: not implemented.
398
399
400
401
402       === Basic file input/output ===
403
404
405       type file_descr
406
407
408       The abstract type of file descriptors.
409
410
411
412       val stdin : file_descr
413
414       File descriptor for standard input.
415
416
417
418       val stdout : file_descr
419
420       File descriptor for standard output.
421
422
423
424       val stderr : file_descr
425
426       File descriptor for standard error.
427
428
429       type open_flag =
430        | O_RDONLY  (* Open for reading
431        *)
432        | O_WRONLY  (* Open for writing
433        *)
434        | O_RDWR  (* Open for reading and writing
435        *)
436        | O_NONBLOCK  (* Open in non-blocking mode
437        *)
438        | O_APPEND  (* Open for append
439        *)
440        | O_CREAT  (* Create if nonexistent
441        *)
442        | O_TRUNC  (* Truncate to 0 length if existing
443        *)
444        | O_EXCL  (* Fail if existing
445        *)
446        | O_NOCTTY  (* Don't make this dev a controlling tty
447        *)
448        | O_DSYNC  (* Writes complete as `Synchronised I/O data integrity com‐
449       pletion'
450        *)
451        |  O_SYNC  (* Writes complete as `Synchronised I/O file integrity com‐
452       pletion'
453        *)
454        | O_RSYNC  (* Reads complete as writes (depending on O_SYNC/O_DSYNC)
455        *)
456        | O_SHARE_DELETE  (* Windows only: allow the file to be deleted  while
457       still open
458        *)
459        |  O_CLOEXEC  (* Set the close-on-exec flag on the descriptor returned
460       by Unix.openfile .  See Unix.set_close_on_exec for more information.
461        *)
462        | O_KEEPEXEC  (* Clear the close-on-exec flag.  This is currently  the
463       default.
464        *)
465
466
467       The flags to Unix.openfile .
468
469
470       type file_perm = int
471
472
473       The type of file access rights, e.g.  0o640 is read and write for user,
474       read for group, none for others
475
476
477
478       val openfile : string -> open_flag list -> file_perm -> file_descr
479
480       Open the named file with the given flags. Third argument is the permis‐
481       sions  to give to the file if it is created (see Unix.umask ). Return a
482       file descriptor on the named file.
483
484
485
486       val close : file_descr -> unit
487
488       Close a file descriptor.
489
490
491
492       val read : file_descr -> bytes -> int -> int -> int
493
494
495       read fd buff ofs len reads len bytes from descriptor fd , storing  them
496       in  byte  sequence buff , starting at position ofs in buff . Return the
497       number of bytes actually read.
498
499
500
501       val write : file_descr -> bytes -> int -> int -> int
502
503
504       write fd buff ofs len writes len bytes to descriptor fd ,  taking  them
505       from byte sequence buff , starting at position ofs in buff . Return the
506       number of bytes actually written.  write repeats the writing  operation
507       until all bytes have been written or an error occurs.
508
509
510
511       val single_write : file_descr -> bytes -> int -> int -> int
512
513       Same  as  write  ,  but attempts to write only once.  Thus, if an error
514       occurs, single_write guarantees that no data has been written.
515
516
517
518       val write_substring : file_descr -> string -> int -> int -> int
519
520       Same as write , but take the data from  a  string  instead  of  a  byte
521       sequence.
522
523
524       Since 4.02.0
525
526
527
528       val single_write_substring : file_descr -> string -> int -> int -> int
529
530       Same  as  single_write  ,  but take the data from a string instead of a
531       byte sequence.
532
533
534       Since 4.02.0
535
536
537
538
539       === Interfacing with the standard input/output library ===
540
541
542       val in_channel_of_descr : file_descr -> Pervasives.in_channel
543
544       Create an input channel reading from the given descriptor.  The channel
545       is  initially  in  binary mode; use set_binary_mode_in ic false if text
546       mode is desired.  Text mode is supported only if the descriptor  refers
547       to  a  file or pipe, but is not supported if it refers to a socket.  On
548       Windows, set_binary_mode_in always fails on channels created with  this
549       function.
550
551       Beware that channels are buffered so more characters may have been read
552       from the file descriptor than those accessed using  channel  functions.
553       Channels also keep a copy of the current position in the file.
554
555       You  need  to explicitly close all channels created with this function.
556       Closing the channel also closes the underlying file descriptor  (unless
557       it was already closed).
558
559
560
561       val out_channel_of_descr : file_descr -> Pervasives.out_channel
562
563       Create  an output channel writing on the given descriptor.  The channel
564       is initially in binary mode; use set_binary_mode_out oc false  if  text
565       mode  is desired.  Text mode is supported only if the descriptor refers
566       to a file or pipe, but is not supported if it refers to a  socket.   On
567       Windows, set_binary_mode_out always fails on channels created with this
568       function.
569
570       Beware that channels are buffered so you may  have  to  flush  them  to
571       ensure  that  all  data has been sent to the file descriptor.  Channels
572       also keep a copy of the current position in the file.
573
574       You need to explicitly close all channels created with  this  function.
575       Closing  the  channel  flushes  the data and closes the underlying file
576       descriptor (unless it has  already  been  closed,  in  which  case  the
577       buffered data is lost).
578
579
580
581       val descr_of_in_channel : Pervasives.in_channel -> file_descr
582
583       Return the descriptor corresponding to an input channel.
584
585
586
587       val descr_of_out_channel : Pervasives.out_channel -> file_descr
588
589       Return the descriptor corresponding to an output channel.
590
591
592
593
594       === Seeking and truncating ===
595
596
597       type seek_command =
598        |  SEEK_SET   (*  indicates positions relative to the beginning of the
599       file
600        *)
601        | SEEK_CUR  (* indicates positions relative to the current position
602        *)
603        | SEEK_END  (* indicates positions relative to the end of the file
604        *)
605
606
607       Positioning modes for Unix.lseek .
608
609
610
611       val lseek : file_descr -> int -> seek_command -> int
612
613       Set the current position for a file descriptor, and return the  result‐
614       ing offset (from the beginning of the file).
615
616
617
618       val truncate : string -> int -> unit
619
620       Truncates the named file to the given size.
621
622       On Windows: not implemented.
623
624
625
626       val ftruncate : file_descr -> int -> unit
627
628       Truncates  the  file corresponding to the given descriptor to the given
629       size.
630
631       On Windows: not implemented.
632
633
634
635
636       === File status ===
637
638
639       type file_kind =
640        | S_REG  (* Regular file
641        *)
642        | S_DIR  (* Directory
643        *)
644        | S_CHR  (* Character device
645        *)
646        | S_BLK  (* Block device
647        *)
648        | S_LNK  (* Symbolic link
649        *)
650        | S_FIFO  (* Named pipe
651        *)
652        | S_SOCK  (* Socket
653        *)
654
655
656
657
658       type stats = {
659        st_dev : int ;  (* Device number
660        *)
661        st_ino : int ;  (* Inode number
662        *)
663        st_kind : file_kind ;  (* Kind of the file
664        *)
665        st_perm : file_perm ;  (* Access rights
666        *)
667        st_nlink : int ;  (* Number of links
668        *)
669        st_uid : int ;  (* User id of the owner
670        *)
671        st_gid : int ;  (* Group ID of the file's group
672        *)
673        st_rdev : int ;  (* Device minor number
674        *)
675        st_size : int ;  (* Size in bytes
676        *)
677        st_atime : float ;  (* Last access time
678        *)
679        st_mtime : float ;  (* Last modification time
680        *)
681        st_ctime : float ;  (* Last status change time
682        *)
683        }
684
685
686       The information returned by the Unix.stat calls.
687
688
689
690       val stat : string -> stats
691
692       Return the information for the named file.
693
694
695
696       val lstat : string -> stats
697
698       Same as Unix.stat , but in case the file is a symbolic link, return the
699       information for the link itself.
700
701
702
703       val fstat : file_descr -> stats
704
705       Return  the information for the file associated with the given descrip‐
706       tor.
707
708
709
710       val isatty : file_descr -> bool
711
712       Return true if the given file descriptor refers to a terminal  or  con‐
713       sole window, false otherwise.
714
715
716
717
718       === File operations on large files ===
719
720
721       module LargeFile : sig end
722
723
724       File  operations on large files.  This sub-module provides 64-bit vari‐
725       ants of the functions Unix.lseek (for positioning a  file  descriptor),
726       Unix.truncate and Unix.ftruncate (for changing the size of a file), and
727       Unix.stat , Unix.lstat and Unix.fstat  (for  obtaining  information  on
728       files).   These  alternate  functions  represent positions and sizes by
729       64-bit integers (type int64 ) instead of regular integers (type int  ),
730       thus allowing operating on files whose sizes are greater than max_int .
731
732
733
734
735       === Mapping files into memory ===
736
737
738       val map_file : file_descr -> ?pos:int64 -> ('a, 'b) Bigarray.kind -> 'c
739       Bigarray.layout -> bool -> int array -> ('a,  'b,  'c)  Bigarray.Genar‐
740       ray.t
741
742       Memory  mapping  of  a  file  as  a big array.  map_file fd kind layout
743       shared dims returns a big array of kind kind  ,  layout  layout  ,  and
744       dimensions as specified in dims .  The data contained in this big array
745       are the contents of the file referred to by the file descriptor fd  (as
746       opened  previously with Unix.openfile , for example).  The optional pos
747       parameter is the byte offset in the file of the data being  mapped;  it
748       defaults to 0 (map from the beginning of the file).
749
750       If  shared  is  true  ,  all  modifications  performed on the array are
751       reflected in the file.  This requires that fd be opened with write per‐
752       missions.   If  shared  is false , modifications performed on the array
753       are done in memory only, using copy-on-write of the modified pages; the
754       underlying file is not affected.
755
756
757       Genarray.map_file is much more efficient than reading the whole file in
758       a big array, modifying that big array, and writing it afterwards.
759
760       To adjust automatically the dimensions of the big array to  the  actual
761       size of the file, the major dimension (that is, the first dimension for
762       an array with C layout, and the last dimension for an array  with  For‐
763       tran  layout)  can  be given as -1 .  Genarray.map_file then determines
764       the major dimension from the size of the file.  The file  must  contain
765       an  integral number of sub-arrays as determined by the non-major dimen‐
766       sions, otherwise Failure is raised.
767
768       If all dimensions of the big array are given, the file size is  matched
769       against  the size of the big array.  If the file is larger than the big
770       array, only the initial portion of the file is mapped to the big array.
771       If  the  file  is smaller than the big array, the file is automatically
772       grown to the size of the big array.  This requires write permissions on
773       fd .
774
775       Array accesses are bounds-checked, but the bounds are determined by the
776       initial call to map_file . Therefore, you should  make  sure  no  other
777       process modifies the mapped file while you're accessing it, or a SIGBUS
778       signal may be raised. This  happens,  for  instance,  if  the  file  is
779       shrunk.
780
781
782       Invalid_argument or Failure may be raised in cases where argument vali‐
783       dation fails.
784
785
786       Since 4.06.0
787
788
789
790
791       === Operations on file names ===
792
793
794       val unlink : string -> unit
795
796       Removes the named file.
797
798       If the named file is a directory, raises:
799
800       - EPERM on POSIX compliant system
801
802       - EISDIR on Linux >= 2.1.132
803
804       - EACCESS on Windows
805
806
807
808
809       val rename : string -> string -> unit
810
811
812       rename old new changes the name of a file from old to new ,  moving  it
813       between  directories  if  needed.   If new already exists, its contents
814       will be replaced with those of old .  Depending on the  operating  sys‐
815       tem,  the  metadata (permissions, owner, etc) of new can either be pre‐
816       served or be replaced by those of old .
817
818
819
820       val link : string -> string -> unit
821
822
823       link source dest creates a hard link  named  dest  to  the  file  named
824       source .
825
826
827
828
829       === File permissions and ownership ===
830
831
832       type access_permission =
833        | R_OK  (* Read permission
834        *)
835        | W_OK  (* Write permission
836        *)
837        | X_OK  (* Execution permission
838        *)
839        | F_OK  (* File exists
840        *)
841
842
843       Flags for the Unix.access call.
844
845
846
847       val chmod : string -> file_perm -> unit
848
849       Change the permissions of the named file.
850
851
852
853       val fchmod : file_descr -> file_perm -> unit
854
855       Change the permissions of an opened file.  On Windows: not implemented.
856
857
858
859       val chown : string -> int -> int -> unit
860
861       Change  the owner uid and owner gid of the named file.  On Windows: not
862       implemented (make no sense on a DOS file system).
863
864
865
866       val fchown : file_descr -> int -> int -> unit
867
868       Change the owner uid and owner gid of an opened file.  On Windows:  not
869       implemented (make no sense on a DOS file system).
870
871
872
873       val umask : int -> int
874
875       Set  the  process's  file  mode  creation mask, and return the previous
876       mask.  On Windows: not implemented.
877
878
879
880       val access : string -> access_permission list -> unit
881
882       Check that the process has the given permissions over the named file.
883
884
885       Raises Unix_error otherwise.
886
887       On Windows, execute permission X_OK , cannot be tested, it  just  tests
888       for read permission instead.
889
890
891
892
893       === Operations on file descriptors ===
894
895
896       val dup : ?cloexec:bool -> file_descr -> file_descr
897
898       Return  a  new  file  descriptor referencing the same file as the given
899       descriptor.   See  Unix.set_close_on_exec  for  documentation  on   the
900       cloexec optional argument.
901
902
903
904       val dup2 : ?cloexec:bool -> file_descr -> file_descr -> unit
905
906
907       dup2  fd1  fd2  duplicates  fd1 to fd2 , closing fd2 if already opened.
908       See Unix.set_close_on_exec for documentation on  the  cloexec  optional
909       argument.
910
911
912
913       val set_nonblock : file_descr -> unit
914
915       Set  the  ``non-blocking''  flag  on  the  given  descriptor.  When the
916       non-blocking flag is set, reading on a descriptor  on  which  there  is
917       temporarily  no  data  available raises the EAGAIN or EWOULDBLOCK error
918       instead of blocking; writing on a descriptor on which there  is  tempo‐
919       rarily no room for writing also raises EAGAIN or EWOULDBLOCK .
920
921
922
923       val clear_nonblock : file_descr -> unit
924
925       Clear   the   ``non-blocking''  flag  on  the  given  descriptor.   See
926       Unix.set_nonblock .
927
928
929
930       val set_close_on_exec : file_descr -> unit
931
932       Set the ``close-on-exec'' flag on the given descriptor.   A  descriptor
933       with  the  close-on-exec  flag is automatically closed when the current
934       process starts another program with one of the  exec  ,  create_process
935       and open_process functions.
936
937       It  is often a security hole to leak file descriptors opened on, say, a
938       private file to an external program: the program, then, gets access  to
939       the  private  file  and can do bad things with it.  Hence, it is highly
940       recommended to set all file descriptors  ``close-on-exec'',  except  in
941       the  very few cases where a file descriptor actually needs to be trans‐
942       mitted to another program.
943
944       The best way to set a file descriptor ``close-on-exec'' is to create it
945       in  this  state.   To this end, the openfile function has O_CLOEXEC and
946       O_KEEPEXEC flags to enforce ``close-on-exec'' mode or  ``keep-on-exec''
947       mode,  respectively.  All other operations in the Unix module that cre‐
948       ate file descriptors have an optional argument ?cloexec:bool  to  indi‐
949       cate whether the file descriptor should be created in ``close-on-exec''
950       mode (by writing ~cloexec:true ) or in ``keep-on-exec'' mode (by  writ‐
951       ing  ~cloexec:false  ).   For  historical  reasons,  the  default  file
952       descriptor creation mode is ``keep-on-exec'', if  no  cloexec  optional
953       argument is given.  This is not a safe default, hence it is highly rec‐
954       ommended to pass explicit cloexec arguments to operations  that  create
955       file descriptors.
956
957       The  cloexec optional arguments and the O_KEEPEXEC flag were introduced
958       in OCaml 4.05.   Earlier,  the  common  practice  was  to  create  file
959       descriptors   in   the   default,   ``keep-on-exec''  mode,  then  call
960       set_close_on_exec on those freshly-created file descriptors.   This  is
961       not  as  safe as creating the file descriptor in ``close-on-exec'' mode
962       because, in multithreaded programs, a window  of  vulnerability  exists
963       between  the  time  when  the  file  descriptor is created and the time
964       set_close_on_exec completes.  If another thread spawns another  program
965       during  this  window,  the  descriptor will leak, as it is still in the
966       ``keep-on-exec'' mode.
967
968       Regarding the atomicity guarantees given by ~cloexec:true or by the use
969       of the O_CLOEXEC flag: on all platforms it is guaranteed that a concur‐
970       rently-executing Caml thread cannot leak the descriptor by  starting  a
971       new  process.  On Linux, this guarantee extends to concurrently-execut‐
972       ing C threads.  As of Feb 2017, other operating systems lack the neces‐
973       sary  system  calls  and  still expose a window of vulnerability during
974       which  a  C  thread  can  see  the  newly-created  file  descriptor  in
975       ``keep-on-exec'' mode.
976
977
978
979       val clear_close_on_exec : file_descr -> unit
980
981       Clear   the  ``close-on-exec''  flag  on  the  given  descriptor.   See
982       Unix.set_close_on_exec .
983
984
985
986
987       === Directories ===
988
989
990       val mkdir : string -> file_perm -> unit
991
992       Create a directory with the given permissions (see Unix.umask ).
993
994
995
996       val rmdir : string -> unit
997
998       Remove an empty directory.
999
1000
1001
1002       val chdir : string -> unit
1003
1004       Change the process working directory.
1005
1006
1007
1008       val getcwd : unit -> string
1009
1010       Return the name of the current working directory.
1011
1012
1013
1014       val chroot : string -> unit
1015
1016       Change the process root directory.  On Windows: not implemented.
1017
1018
1019       type dir_handle
1020
1021
1022       The type of descriptors over opened directories.
1023
1024
1025
1026       val opendir : string -> dir_handle
1027
1028       Open a descriptor on a directory
1029
1030
1031
1032       val readdir : dir_handle -> string
1033
1034       Return the next entry in a directory.
1035
1036
1037       Raises End_of_file when the end of the directory has been reached.
1038
1039
1040
1041       val rewinddir : dir_handle -> unit
1042
1043       Reposition the descriptor to the beginning of the directory
1044
1045
1046
1047       val closedir : dir_handle -> unit
1048
1049       Close a directory descriptor.
1050
1051
1052
1053
1054       === Pipes and redirections ===
1055
1056
1057       val pipe : ?cloexec:bool -> unit -> file_descr * file_descr
1058
1059       Create a pipe. The first component of the result is opened for reading,
1060       that's  the  exit to the pipe. The second component is opened for writ‐
1061       ing, that's the entrance to the pipe.  See  Unix.set_close_on_exec  for
1062       documentation on the cloexec optional argument.
1063
1064
1065
1066       val mkfifo : string -> file_perm -> unit
1067
1068       Create  a  named pipe with the given permissions (see Unix.umask ).  On
1069       Windows: not implemented.
1070
1071
1072
1073
1074       === High-level process and redirection management ===
1075
1076
1077       val create_process : string -> string array -> file_descr -> file_descr
1078       -> file_descr -> int
1079
1080
1081       create_process  prog  args  new_stdin new_stdout new_stderr forks a new
1082       process that executes the program in file prog , with arguments args  .
1083       The  pid  of  the  new process is returned immediately; the new process
1084       executes concurrently with the current process.  The standard input and
1085       outputs of the new process are connected to the descriptors new_stdin ,
1086       new_stdout and new_stderr .  Passing e.g.  stdout for  new_stdout  pre‐
1087       vents the redirection and causes the new process to have the same stan‐
1088       dard output as the  current  process.   The  executable  file  prog  is
1089       searched  in the path.  The new process has the same environment as the
1090       current process.
1091
1092
1093
1094       val create_process_env : string -> string  array  ->  string  array  ->
1095       file_descr -> file_descr -> file_descr -> int
1096
1097
1098       create_process_env  prog args env new_stdin new_stdout new_stderr works
1099       as Unix.create_process , except that the extra argument  env  specifies
1100       the environment passed to the program.
1101
1102
1103
1104       val open_process_in : string -> Pervasives.in_channel
1105
1106       High-level  pipe  and  process management. This function runs the given
1107       command in parallel with the program.  The standard output of the  com‐
1108       mand  is redirected to a pipe, which can be read via the returned input
1109       channel.  The command is interpreted by the shell /bin/sh  (or  cmd.exe
1110       on Windows), cf.  system .
1111
1112
1113
1114       val open_process_out : string -> Pervasives.out_channel
1115
1116       Same  as  Unix.open_process_in , but redirect the standard input of the
1117       command to a pipe.  Data written to the returned output channel is sent
1118       to  the standard input of the command.  Warning: writes on output chan‐
1119       nels are buffered, hence be careful to  call  Pervasives.flush  at  the
1120       right times to ensure correct synchronization.
1121
1122
1123
1124       val   open_process   :   string   ->   Pervasives.in_channel  *  Perva‐
1125       sives.out_channel
1126
1127       Same as Unix.open_process_out , but redirects both the  standard  input
1128       and  standard  output  of  the  command  to  pipes connected to the two
1129       returned channels.  The input channel is connected to the output of the
1130       command, and the output channel to the input of the command.
1131
1132
1133
1134       val open_process_full : string -> string array -> Pervasives.in_channel
1135       * Pervasives.out_channel * Pervasives.in_channel
1136
1137       Similar to Unix.open_process , but the second  argument  specifies  the
1138       environment  passed to the command.  The result is a triple of channels
1139       connected respectively to the  standard  output,  standard  input,  and
1140       standard error of the command.
1141
1142
1143
1144       val close_process_in : Pervasives.in_channel -> process_status
1145
1146       Close channels opened by Unix.open_process_in , wait for the associated
1147       command to terminate, and return its termination status.
1148
1149
1150
1151       val close_process_out : Pervasives.out_channel -> process_status
1152
1153       Close channels opened by Unix.open_process_out , wait for  the  associ‐
1154       ated command to terminate, and return its termination status.
1155
1156
1157
1158       val  close_process  : Pervasives.in_channel * Pervasives.out_channel ->
1159       process_status
1160
1161       Close channels opened by Unix.open_process , wait  for  the  associated
1162       command to terminate, and return its termination status.
1163
1164
1165
1166       val close_process_full : Pervasives.in_channel * Pervasives.out_channel
1167       * Pervasives.in_channel -> process_status
1168
1169       Close channels opened by Unix.open_process_full , wait for the  associ‐
1170       ated command to terminate, and return its termination status.
1171
1172
1173
1174
1175       === Symbolic links ===
1176
1177
1178       val symlink : ?to_dir:bool -> string -> string -> unit
1179
1180
1181       symlink ?to_dir source dest creates the file dest as a symbolic link to
1182       the file source . On Windows, ~to_dir indicates if  the  symbolic  link
1183       points  to  a  directory or a file; if omitted, symlink examines source
1184       using stat and picks appropriately, if source does not exist then false
1185       is assumed (for this reason, it is recommended that the ~to_dir parame‐
1186       ter be specified in new code). On Unix, ~to_dir is ignored.
1187
1188       Windows symbolic links are available in Windows  Vista  onwards.  There
1189       are some important differences between Windows symlinks and their POSIX
1190       counterparts.
1191
1192       Windows symbolic links come in two  flavours:  directory  and  regular,
1193       which  designate  whether  the symbolic link points to a directory or a
1194       file. The type must be correct - a  directory  symlink  which  actually
1195       points to a file cannot be selected with chdir and a file symlink which
1196       actually points to a directory cannot be read  or  written  (note  that
1197       Cygwin's emulation layer ignores this distinction).
1198
1199       When  symbolic  links are created to existing targets, this distinction
1200       doesn't matter and symlink will automatically create the  correct  kind
1201       of  symbolic link. The distinction matters when a symbolic link is cre‐
1202       ated to a non-existent target.
1203
1204       The other caveat is that by default symbolic  links  are  a  privileged
1205       operation.  Administrators  will always need to be running elevated (or
1206       with UAC disabled) and by default  normal  user  accounts  need  to  be
1207       granted  the  SeCreateSymbolicLinkPrivilege  via  Local Security Policy
1208       (secpol.msc) or via Active Directory.
1209
1210
1211       Unix.has_symlink can be used to check that a process is able to  create
1212       symbolic links.
1213
1214
1215
1216       val has_symlink : unit -> bool
1217
1218       Returns  true if the user is able to create symbolic links. On Windows,
1219       this indicates that the user not only has the SeCreateSymbolicLinkPriv‐
1220       ilege  but  is also running elevated, if necessary. On other platforms,
1221       this is simply indicates that the symlink system call is available.
1222
1223
1224       Since 4.03.0
1225
1226
1227
1228       val readlink : string -> string
1229
1230       Read the contents of a symbolic link.
1231
1232
1233
1234
1235       === Polling ===
1236
1237
1238       val select : file_descr list -> file_descr list -> file_descr  list  ->
1239       float -> file_descr list * file_descr list * file_descr list
1240
1241       Wait  until  some input/output operations become possible on some chan‐
1242       nels. The three list arguments are, respectively, a set of  descriptors
1243       to  check  for reading (first argument), for writing (second argument),
1244       or for exceptional conditions (third argument).  The fourth argument is
1245       the  maximal  timeout,  in seconds; a negative fourth argument means no
1246       timeout (unbounded wait).  The result is  composed  of  three  sets  of
1247       descriptors: those ready for reading (first component), ready for writ‐
1248       ing (second component), and over  which  an  exceptional  condition  is
1249       pending (third component).
1250
1251
1252
1253
1254       === Locking ===
1255
1256
1257       type lock_command =
1258        | F_ULOCK  (* Unlock a region
1259        *)
1260        | F_LOCK  (* Lock a region for writing, and block if already locked
1261        *)
1262        | F_TLOCK  (* Lock a region for writing, or fail if already locked
1263        *)
1264        | F_TEST  (* Test a region for other process locks
1265        *)
1266        | F_RLOCK  (* Lock a region for reading, and block if already locked
1267        *)
1268        | F_TRLOCK  (* Lock a region for reading, or fail if already locked
1269        *)
1270
1271
1272       Commands for Unix.lockf .
1273
1274
1275
1276       val lockf : file_descr -> lock_command -> int -> unit
1277
1278
1279       lockf  fd  cmd  size puts a lock on a region of the file opened as fd .
1280       The region starts at the current read/write position for fd (as set  by
1281       Unix.lseek  ), and extends size bytes forward if size is positive, size
1282       bytes backwards if size is negative, or to the end of the file if  size
1283       is zero.  A write lock prevents any other process from acquiring a read
1284       or write lock on the region.  A read lock prevents  any  other  process
1285       from  acquiring  a  write  lock on the region, but lets other processes
1286       acquire read locks on it.
1287
1288       The F_LOCK and F_TLOCK commands attempts to put a  write  lock  on  the
1289       specified  region.  The F_RLOCK and F_TRLOCK commands attempts to put a
1290       read lock on the specified region.  If one  or  several  locks  put  by
1291       another  process  prevent  the current process from acquiring the lock,
1292       F_LOCK and F_RLOCK block until these locks are removed,  while  F_TLOCK
1293       and  F_TRLOCK  fail immediately with an exception.  The F_ULOCK removes
1294       whatever locks  the  current  process  has  on  the  specified  region.
1295       Finally,  the F_TEST command tests whether a write lock can be acquired
1296       on the specified region, without actually putting a lock.   It  returns
1297       immediately if successful, or fails otherwise.
1298
1299       What  happens  when  a process tries to lock a region of a file that is
1300       already locked by the same process depends on the OS.  On POSIX-compli‐
1301       ant  systems,  the second lock operation succeeds and may "promote" the
1302       older lock from read lock to write lock.  On Windows, the  second  lock
1303       operation will block or fail.
1304
1305
1306
1307
1308       ===  Signals Note: installation of signal handlers is performed via the
1309       functions Sys.signal and Sys.set_signal. ===
1310
1311
1312       val kill : int -> int -> unit
1313
1314
1315       kill pid sig sends signal number sig to the process with id pid  .   On
1316       Windows, only the Sys.sigkill signal is emulated.
1317
1318
1319       type sigprocmask_command =
1320        | SIG_SETMASK
1321        | SIG_BLOCK
1322        | SIG_UNBLOCK
1323
1324
1325
1326
1327
1328       val sigprocmask : sigprocmask_command -> int list -> int list
1329
1330
1331       sigprocmask  cmd  sigs  changes  the set of blocked signals.  If cmd is
1332       SIG_SETMASK , blocked signals are set to those in the list sigs  .   If
1333       cmd  is SIG_BLOCK , the signals in sigs are added to the set of blocked
1334       signals.  If cmd is SIG_UNBLOCK , the signals in sigs are removed  from
1335       the  set of blocked signals.  sigprocmask returns the set of previously
1336       blocked signals.
1337
1338       On Windows: not implemented (no inter-process signals on Windows).
1339
1340
1341
1342       val sigpending : unit -> int list
1343
1344       Return the set of blocked signals that are currently pending.
1345
1346       On Windows: not implemented (no inter-process signals on Windows).
1347
1348
1349
1350       val sigsuspend : int list -> unit
1351
1352
1353       sigsuspend sigs atomically sets the blocked signals to sigs  and  waits
1354       for  a non-ignored, non-blocked signal to be delivered.  On return, the
1355       blocked signals are reset to their initial value.
1356
1357       On Windows: not implemented (no inter-process signals on Windows).
1358
1359
1360
1361       val pause : unit -> unit
1362
1363       Wait until a non-ignored, non-blocked signal is delivered.
1364
1365       On Windows: not implemented (no inter-process signals on Windows).
1366
1367
1368
1369
1370       === Time functions ===
1371
1372
1373       type process_times = {
1374        tms_utime : float ;  (* User time for the process
1375        *)
1376        tms_stime : float ;  (* System time for the process
1377        *)
1378        tms_cutime : float ;  (* User time for the children processes
1379        *)
1380        tms_cstime : float ;  (* System time for the children processes
1381        *)
1382        }
1383
1384
1385       The execution times (CPU times) of a process.
1386
1387
1388       type tm = {
1389        tm_sec : int ;  (* Seconds 0..60
1390        *)
1391        tm_min : int ;  (* Minutes 0..59
1392        *)
1393        tm_hour : int ;  (* Hours 0..23
1394        *)
1395        tm_mday : int ;  (* Day of month 1..31
1396        *)
1397        tm_mon : int ;  (* Month of year 0..11
1398        *)
1399        tm_year : int ;  (* Year - 1900
1400        *)
1401        tm_wday : int ;  (* Day of week (Sunday is 0)
1402        *)
1403        tm_yday : int ;  (* Day of year 0..365
1404        *)
1405        tm_isdst : bool ;  (* Daylight time savings in effect
1406        *)
1407        }
1408
1409
1410       The type representing wallclock time and calendar date.
1411
1412
1413
1414       val time : unit -> float
1415
1416       Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.
1417
1418
1419
1420       val gettimeofday : unit -> float
1421
1422       Same as Unix.time , but with resolution better than 1 second.
1423
1424
1425
1426       val gmtime : float -> tm
1427
1428       Convert a time in seconds, as returned by Unix.time , into a date and a
1429       time.  Assumes UTC (Coordinated Universal Time), also known as GMT.  To
1430       perform the inverse conversion, set  the  TZ  environment  variable  to
1431       "UTC", use Unix.mktime , and then restore the original value of TZ.
1432
1433
1434
1435       val localtime : float -> tm
1436
1437       Convert a time in seconds, as returned by Unix.time , into a date and a
1438       time. Assumes the local time zone.  The function performing the inverse
1439       conversion is Unix.mktime .
1440
1441
1442
1443       val mktime : tm -> float * tm
1444
1445       Convert  a  date and time, specified by the tm argument, into a time in
1446       seconds, as returned by Unix.time .  The tm_isdst , tm_wday and tm_yday
1447       fields  of  tm are ignored.  Also return a normalized copy of the given
1448       tm record, with the tm_wday , tm_yday , and tm_isdst fields  recomputed
1449       from  the other fields, and the other fields normalized (so that, e.g.,
1450       40 October is changed into 9 November).  The tm argument is interpreted
1451       in the local time zone.
1452
1453
1454
1455       val alarm : int -> int
1456
1457       Schedule a SIGALRM signal after the given number of seconds.
1458
1459       On Windows: not implemented.
1460
1461
1462
1463       val sleep : int -> unit
1464
1465       Stop execution for the given number of seconds.
1466
1467
1468
1469       val sleepf : float -> unit
1470
1471       Stop execution for the given number of seconds.  Like sleep , but frac‐
1472       tions of seconds are supported.
1473
1474
1475       Since 4.03.0
1476
1477
1478
1479       val times : unit -> process_times
1480
1481       Return the execution times of the process.  On Windows, it is partially
1482       implemented, will not report timings for child processes.
1483
1484
1485
1486       val utimes : string -> float -> float -> unit
1487
1488       Set the last access time (second arg) and last modification time (third
1489       arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan.
1490       1,  1970.   If  both  times  are 0.0 , the access and last modification
1491       times are both set to the current time.
1492
1493
1494       type interval_timer =
1495        | ITIMER_REAL  (* decrements  in  real  time,  and  sends  the  signal
1496       SIGALRM when expired.
1497        *)
1498        |  ITIMER_VIRTUAL   (*  decrements  in process virtual time, and sends
1499       SIGVTALRM when expired.
1500        *)
1501        | ITIMER_PROF  (* (for profiling) decrements both when the process  is
1502       running  and  when  the  system is running on behalf of the process; it
1503       sends SIGPROF when expired.
1504        *)
1505
1506
1507       The three kinds of interval timers.
1508
1509
1510       type interval_timer_status = {
1511        it_interval : float ;  (* Period
1512        *)
1513        it_value : float ;  (* Current value of the timer
1514        *)
1515        }
1516
1517
1518       The type describing the status of an interval timer
1519
1520
1521
1522       val getitimer : interval_timer -> interval_timer_status
1523
1524       Return the current status of the given interval timer.
1525
1526       On Windows: not implemented.
1527
1528
1529
1530       val setitimer  :  interval_timer  ->  interval_timer_status  ->  inter‐
1531       val_timer_status
1532
1533
1534       setitimer  t  s sets the interval timer t and returns its previous sta‐
1535       tus. The s argument is interpreted as follows: s.it_value , if nonzero,
1536       is  the  time to the next timer expiration; s.it_interval , if nonzero,
1537       specifies a value to be used  in  reloading  it_value  when  the  timer
1538       expires.   Setting  s.it_value  to  zero  disables  the timer.  Setting
1539       s.it_interval to zero causes the timer to be disabled  after  its  next
1540       expiration.
1541
1542       On Windows: not implemented.
1543
1544
1545
1546
1547       === User id, group id ===
1548
1549
1550       val getuid : unit -> int
1551
1552       Return  the  user  id  of  the user executing the process.  On Windows,
1553       always return 1 .
1554
1555
1556
1557       val geteuid : unit -> int
1558
1559       Return the effective user id under which the process runs.  On Windows,
1560       always return 1 .
1561
1562
1563
1564       val setuid : int -> unit
1565
1566       Set  the  real  user id and effective user id for the process.  On Win‐
1567       dows: not implemented.
1568
1569
1570
1571       val getgid : unit -> int
1572
1573       Return the group id of the user executing  the  process.   On  Windows,
1574       always return 1 .
1575
1576
1577
1578       val getegid : unit -> int
1579
1580       Return  the  effective  group id under which the process runs.  On Win‐
1581       dows, always return 1 .
1582
1583
1584
1585       val setgid : int -> unit
1586
1587       Set the real group id and effective group id for the process.  On  Win‐
1588       dows: not implemented.
1589
1590
1591
1592       val getgroups : unit -> int array
1593
1594       Return  the  list  of  groups  to  which the user executing the process
1595       belongs.  On Windows, always return [|1|] .
1596
1597
1598
1599       val setgroups : int array -> unit
1600
1601
1602       setgroups groups sets the  supplementary  group  IDs  for  the  calling
1603       process.  Appropriate  privileges are required.  On Windows: not imple‐
1604       mented.
1605
1606
1607
1608       val initgroups : string -> int -> unit
1609
1610
1611       initgroups user group initializes the group access list by reading  the
1612       group  database /etc/group and using all groups of which user is a mem‐
1613       ber. The additional group group is also added to the list.  On Windows:
1614       not implemented.
1615
1616
1617       type passwd_entry = {
1618        pw_name : string ;
1619        pw_passwd : string ;
1620        pw_uid : int ;
1621        pw_gid : int ;
1622        pw_gecos : string ;
1623        pw_dir : string ;
1624        pw_shell : string ;
1625        }
1626
1627
1628       Structure of entries in the passwd database.
1629
1630
1631       type group_entry = {
1632        gr_name : string ;
1633        gr_passwd : string ;
1634        gr_gid : int ;
1635        gr_mem : string array ;
1636        }
1637
1638
1639       Structure of entries in the groups database.
1640
1641
1642
1643       val getlogin : unit -> string
1644
1645       Return the login name of the user executing the process.
1646
1647
1648
1649       val getpwnam : string -> passwd_entry
1650
1651       Find an entry in passwd with the given name.
1652
1653
1654       Raises Not_found if no such entry exist.
1655
1656       On Windows, always raise Not_found .
1657
1658
1659
1660       val getgrnam : string -> group_entry
1661
1662       Find an entry in group with the given name.
1663
1664
1665       Raises Not_found if no such entry exist.
1666
1667       On Windows, always raise Not_found .
1668
1669
1670
1671       val getpwuid : int -> passwd_entry
1672
1673       Find an entry in passwd with the given user id.
1674
1675
1676       Raises Not_found if no such entry exist.
1677
1678       On Windows, always raise Not_found .
1679
1680
1681
1682       val getgrgid : int -> group_entry
1683
1684       Find an entry in group with the given group id.
1685
1686
1687       Raises Not_found if no such entry exist.
1688
1689       On Windows, always raise Not_found .
1690
1691
1692
1693
1694       === Internet addresses ===
1695
1696
1697       type inet_addr
1698
1699
1700       The abstract type of Internet addresses.
1701
1702
1703
1704       val inet_addr_of_string : string -> inet_addr
1705
1706       Conversion  from the printable representation of an Internet address to
1707       its internal representation.  The argument string consists of 4 numbers
1708       separated  by periods ( XXX.YYY.ZZZ.TTT ) for IPv4 addresses, and up to
1709       8 numbers separated by colons for IPv6 addresses.
1710
1711
1712       Raises Failure when given a string that does not match these formats.
1713
1714
1715
1716       val string_of_inet_addr : inet_addr -> string
1717
1718       Return the printable representation of the given Internet address.  See
1719       Unix.inet_addr_of_string for a description of the printable representa‐
1720       tion.
1721
1722
1723
1724       val inet_addr_any : inet_addr
1725
1726       A special IPv4 address, for use only with bind , representing  all  the
1727       Internet addresses that the host machine possesses.
1728
1729
1730
1731       val inet_addr_loopback : inet_addr
1732
1733       A special IPv4 address representing the host machine ( 127.0.0.1 ).
1734
1735
1736
1737       val inet6_addr_any : inet_addr
1738
1739       A  special  IPv6 address, for use only with bind , representing all the
1740       Internet addresses that the host machine possesses.
1741
1742
1743
1744       val inet6_addr_loopback : inet_addr
1745
1746       A special IPv6 address representing the host machine ( ::1 ).
1747
1748
1749
1750
1751       === Sockets ===
1752
1753
1754       type socket_domain =
1755        | PF_UNIX  (* Unix domain
1756        *)
1757        | PF_INET  (* Internet domain (IPv4)
1758        *)
1759        | PF_INET6  (* Internet domain (IPv6)
1760        *)
1761
1762
1763       The type of socket domains.  Not all  platforms  support  IPv6  sockets
1764       (type PF_INET6 ).  Windows does not support PF_UNIX .
1765
1766
1767       type socket_type =
1768        | SOCK_STREAM  (* Stream socket
1769        *)
1770        | SOCK_DGRAM  (* Datagram socket
1771        *)
1772        | SOCK_RAW  (* Raw socket
1773        *)
1774        | SOCK_SEQPACKET  (* Sequenced packets socket
1775        *)
1776
1777
1778       The  type  of socket kinds, specifying the semantics of communications.
1779       SOCK_SEQPACKET is included for completeness, but is rarely supported by
1780       the OS, and needs system calls that are not available in this library.
1781
1782
1783       type sockaddr =
1784        | ADDR_UNIX of string
1785        | ADDR_INET of inet_addr * int
1786         (*  The type of socket addresses.  ADDR_UNIX name is a socket address
1787       in  the  Unix  domain;  name  is  a  file  name  in  the  file  system.
1788       ADDR_INET(addr,port)  is  a socket address in the Internet domain; addr
1789       is the Internet address of the machine, and port is the port number.
1790        *)
1791
1792
1793
1794
1795
1796       val socket : ?cloexec:bool -> socket_domain -> socket_type  ->  int  ->
1797       file_descr
1798
1799       Create  a  new socket in the given domain, and with the given kind. The
1800       third argument is the protocol type; 0 selects the default protocol for
1801       that  kind of sockets.  See Unix.set_close_on_exec for documentation on
1802       the cloexec optional argument.
1803
1804
1805
1806       val domain_of_sockaddr : sockaddr -> socket_domain
1807
1808       Return the socket domain adequate for the given socket address.
1809
1810
1811
1812       val socketpair : ?cloexec:bool -> socket_domain -> socket_type  ->  int
1813       -> file_descr * file_descr
1814
1815       Create   a   pair   of   unnamed   sockets,  connected  together.   See
1816       Unix.set_close_on_exec for documentation on the cloexec optional  argu‐
1817       ment.
1818
1819
1820
1821       val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr
1822
1823       Accept  connections  on  the given socket. The returned descriptor is a
1824       socket connected to the client; the returned address is the address  of
1825       the connecting client.  See Unix.set_close_on_exec for documentation on
1826       the cloexec optional argument.
1827
1828
1829
1830       val bind : file_descr -> sockaddr -> unit
1831
1832       Bind a socket to an address.
1833
1834
1835
1836       val connect : file_descr -> sockaddr -> unit
1837
1838       Connect a socket to an address.
1839
1840
1841
1842       val listen : file_descr -> int -> unit
1843
1844       Set up a socket for receiving connection requests. The integer argument
1845       is the maximal number of pending requests.
1846
1847
1848       type shutdown_command =
1849        | SHUTDOWN_RECEIVE  (* Close for receiving
1850        *)
1851        | SHUTDOWN_SEND  (* Close for sending
1852        *)
1853        | SHUTDOWN_ALL  (* Close both
1854        *)
1855
1856
1857       The type of commands for shutdown .
1858
1859
1860
1861       val shutdown : file_descr -> shutdown_command -> unit
1862
1863       Shutdown  a socket connection.  SHUTDOWN_SEND as second argument causes
1864       reads on the other end of the connection to return an end-of-file  con‐
1865       dition.  SHUTDOWN_RECEIVE causes writes on the other end of the connec‐
1866       tion to return a closed pipe condition ( SIGPIPE signal).
1867
1868
1869
1870       val getsockname : file_descr -> sockaddr
1871
1872       Return the address of the given socket.
1873
1874
1875
1876       val getpeername : file_descr -> sockaddr
1877
1878       Return the address of the host connected to the given socket.
1879
1880
1881       type msg_flag =
1882        | MSG_OOB
1883        | MSG_DONTROUTE
1884        | MSG_PEEK  (* The flags for Unix.recv , Unix.recvfrom , Unix.send and
1885       Unix.sendto .
1886        *)
1887
1888
1889
1890
1891
1892       val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int
1893
1894       Receive data from a connected socket.
1895
1896
1897
1898       val  recvfrom  :  file_descr -> bytes -> int -> int -> msg_flag list ->
1899       int * sockaddr
1900
1901       Receive data from an unconnected socket.
1902
1903
1904
1905       val send : file_descr -> bytes -> int -> int -> msg_flag list -> int
1906
1907       Send data over a connected socket.
1908
1909
1910
1911       val send_substring : file_descr -> string -> int  ->  int  ->  msg_flag
1912       list -> int
1913
1914       Same  as  send  ,  but  take  the  data from a string instead of a byte
1915       sequence.
1916
1917
1918       Since 4.02.0
1919
1920
1921
1922       val sendto : file_descr -> bytes -> int ->  int  ->  msg_flag  list  ->
1923       sockaddr -> int
1924
1925       Send data over an unconnected socket.
1926
1927
1928
1929       val  sendto_substring  : file_descr -> string -> int -> int -> msg_flag
1930       list -> sockaddr -> int
1931
1932       Same as sendto , but take the data from a  string  instead  of  a  byte
1933       sequence.
1934
1935
1936       Since 4.02.0
1937
1938
1939
1940
1941       === Socket options ===
1942
1943
1944       type socket_bool_option =
1945        | SO_DEBUG  (* Record debugging information
1946        *)
1947        | SO_BROADCAST  (* Permit sending of broadcast messages
1948        *)
1949        | SO_REUSEADDR  (* Allow reuse of local addresses for bind
1950        *)
1951        | SO_KEEPALIVE  (* Keep connection active
1952        *)
1953        | SO_DONTROUTE  (* Bypass the standard routing algorithms
1954        *)
1955        | SO_OOBINLINE  (* Leave out-of-band data in line
1956        *)
1957        | SO_ACCEPTCONN  (* Report whether socket listening is enabled
1958        *)
1959        | TCP_NODELAY  (* Control the Nagle algorithm for TCP sockets
1960        *)
1961        | IPV6_ONLY  (* Forbid binding an IPv6 socket to an IPv4 address
1962        *)
1963
1964
1965       The socket options that can be consulted with Unix.getsockopt and modi‐
1966       fied with Unix.setsockopt .  These options have  a  boolean  (  true  /
1967       false ) value.
1968
1969
1970       type socket_int_option =
1971        | SO_SNDBUF  (* Size of send buffer
1972        *)
1973        | SO_RCVBUF  (* Size of received buffer
1974        *)
1975        | SO_ERROR  (* Deprecated.  Use Unix.getsockopt_error instead.
1976        *)
1977        | SO_TYPE  (* Report the socket type
1978        *)
1979        |  SO_RCVLOWAT  (* Minimum number of bytes to process for input opera‐
1980       tions
1981        *)
1982        | SO_SNDLOWAT  (* Minimum number of bytes to process for output opera‐
1983       tions
1984        *)
1985
1986
1987       The  socket  options that can be consulted with Unix.getsockopt_int and
1988       modified with Unix.setsockopt_int .   These  options  have  an  integer
1989       value.
1990
1991
1992       type socket_optint_option =
1993        | SO_LINGER  (* Whether to linger on closed connections that have data
1994       present, and for how long (in seconds)
1995        *)
1996
1997
1998       The socket options that can be  consulted  with  Unix.getsockopt_optint
1999       and  modified with Unix.setsockopt_optint .  These options have a value
2000       of type int option , with None meaning ``disabled''.
2001
2002
2003       type socket_float_option =
2004        | SO_RCVTIMEO  (* Timeout for input operations
2005        *)
2006        | SO_SNDTIMEO  (* Timeout for output operations
2007        *)
2008
2009
2010       The socket options that can be consulted with Unix.getsockopt_float and
2011       modified  with  Unix.setsockopt_float  .   These  options have a float‐
2012       ing-point value representing a time in  seconds.   The  value  0  means
2013       infinite timeout.
2014
2015
2016
2017       val getsockopt : file_descr -> socket_bool_option -> bool
2018
2019       Return  the  current  status  of  a  boolean-valued option in the given
2020       socket.
2021
2022
2023
2024       val setsockopt : file_descr -> socket_bool_option -> bool -> unit
2025
2026       Set or clear a boolean-valued option in the given socket.
2027
2028
2029
2030       val getsockopt_int : file_descr -> socket_int_option -> int
2031
2032       Same as Unix.getsockopt for an integer-valued socket option.
2033
2034
2035
2036       val setsockopt_int : file_descr -> socket_int_option -> int -> unit
2037
2038       Same as Unix.setsockopt for an integer-valued socket option.
2039
2040
2041
2042       val getsockopt_optint  :  file_descr  ->  socket_optint_option  ->  int
2043       option
2044
2045       Same  as  Unix.getsockopt  for  a  socket  option whose value is an int
2046       option .
2047
2048
2049
2050       val setsockopt_optint  :  file_descr  ->  socket_optint_option  ->  int
2051       option -> unit
2052
2053       Same  as  Unix.setsockopt  for  a  socket  option whose value is an int
2054       option .
2055
2056
2057
2058       val getsockopt_float : file_descr -> socket_float_option -> float
2059
2060       Same as Unix.getsockopt for a socket option whose  value  is  a  float‐
2061       ing-point number.
2062
2063
2064
2065       val  setsockopt_float  :  file_descr -> socket_float_option -> float ->
2066       unit
2067
2068       Same as Unix.setsockopt for a socket option whose  value  is  a  float‐
2069       ing-point number.
2070
2071
2072
2073       val getsockopt_error : file_descr -> error option
2074
2075       Return  the error condition associated with the given socket, and clear
2076       it.
2077
2078
2079
2080
2081       === High-level network connection functions ===
2082
2083
2084       val  open_connection  :  sockaddr  ->  Pervasives.in_channel  *  Perva‐
2085       sives.out_channel
2086
2087       Connect  to  a  server at the given address.  Return a pair of buffered
2088       channels connected to the server.  Remember to call Pervasives.flush on
2089       the  output  channel  at the right times to ensure correct synchroniza‐
2090       tion.
2091
2092
2093
2094       val shutdown_connection : Pervasives.in_channel -> unit
2095
2096       ``Shut down'' a connection established with Unix.open_connection ; that
2097       is,  transmit  an  end-of-file  condition  to the server reading on the
2098       other side of the connection.  This  does  not  fully  close  the  file
2099       descriptor associated with the channel, which you must remember to free
2100       via Pervasives.close_in .
2101
2102
2103
2104       val establish_server : (Pervasives.in_channel -> Pervasives.out_channel
2105       -> unit) -> sockaddr -> unit
2106
2107       Establish  a  server on the given address.  The function given as first
2108       argument is called for each connection with two buffered channels  con‐
2109       nected to the client. A new process is created for each connection. The
2110       function Unix.establish_server never returns normally.
2111
2112       On Windows, it is not implemented.  Use threads.
2113
2114
2115
2116
2117       === Host and protocol databases ===
2118
2119
2120       type host_entry = {
2121        h_name : string ;
2122        h_aliases : string array ;
2123        h_addrtype : socket_domain ;
2124        h_addr_list : inet_addr array ;
2125        }
2126
2127
2128       Structure of entries in the hosts database.
2129
2130
2131       type protocol_entry = {
2132        p_name : string ;
2133        p_aliases : string array ;
2134        p_proto : int ;
2135        }
2136
2137
2138       Structure of entries in the protocols database.
2139
2140
2141       type service_entry = {
2142        s_name : string ;
2143        s_aliases : string array ;
2144        s_port : int ;
2145        s_proto : string ;
2146        }
2147
2148
2149       Structure of entries in the services database.
2150
2151
2152
2153       val gethostname : unit -> string
2154
2155       Return the name of the local host.
2156
2157
2158
2159       val gethostbyname : string -> host_entry
2160
2161       Find an entry in hosts with the given name.
2162
2163
2164       Raises Not_found if no such entry exist.
2165
2166
2167
2168       val gethostbyaddr : inet_addr -> host_entry
2169
2170       Find an entry in hosts with the given address.
2171
2172
2173       Raises Not_found if no such entry exist.
2174
2175
2176
2177       val getprotobyname : string -> protocol_entry
2178
2179       Find an entry in protocols with the given name.
2180
2181
2182       Raises Not_found if no such entry exist.
2183
2184
2185
2186       val getprotobynumber : int -> protocol_entry
2187
2188       Find an entry in protocols with the given protocol number.
2189
2190
2191       Raises Not_found if no such entry exist.
2192
2193
2194
2195       val getservbyname : string -> string -> service_entry
2196
2197       Find an entry in services with the given name.
2198
2199
2200       Raises Not_found if no such entry exist.
2201
2202
2203
2204       val getservbyport : int -> string -> service_entry
2205
2206       Find an entry in services with the given service number.
2207
2208
2209       Raises Not_found if no such entry exist.
2210
2211
2212       type addr_info = {
2213        ai_family : socket_domain ;  (* Socket domain
2214        *)
2215        ai_socktype : socket_type ;  (* Socket type
2216        *)
2217        ai_protocol : int ;  (* Socket protocol number
2218        *)
2219        ai_addr : sockaddr ;  (* Address
2220        *)
2221        ai_canonname : string ;  (* Canonical host name
2222        *)
2223        }
2224
2225
2226       Address information returned by Unix.getaddrinfo .
2227
2228
2229       type getaddrinfo_option =
2230        | AI_FAMILY of socket_domain
2231         (* Impose the given socket domain
2232        *)
2233        | AI_SOCKTYPE of socket_type
2234         (* Impose the given socket type
2235        *)
2236        | AI_PROTOCOL of int
2237         (* Impose the given protocol
2238        *)
2239        | AI_NUMERICHOST  (* Do not call  name  resolver,  expect  numeric  IP
2240       address
2241        *)
2242        | AI_CANONNAME  (* Fill the ai_canonname field of the result
2243        *)
2244        | AI_PASSIVE  (* Set address to ``any'' address for use with Unix.bind
2245
2246        *)
2247
2248
2249       Options to Unix.getaddrinfo .
2250
2251
2252
2253       val  getaddrinfo  :  string  ->  string  ->  getaddrinfo_option list ->
2254       addr_info list
2255
2256
2257       getaddrinfo host service opts returns a list of Unix.addr_info  records
2258       describing  socket  parameters and addresses suitable for communicating
2259       with the given host and service.  The empty list  is  returned  if  the
2260       host or service names are unknown, or the constraints expressed in opts
2261       cannot be satisfied.
2262
2263
2264       host is either a host name  or  the  string  representation  of  an  IP
2265       address.   host  can  be  given  as the empty string; in this case, the
2266       ``any'' address or the ``loopback'' address are used, depending whether
2267       opts  contains  AI_PASSIVE  .   service is either a service name or the
2268       string representation of a port number.  service can be  given  as  the
2269       empty string; in this case, the port field of the returned addresses is
2270       set to 0.  opts is a possibly empty list of  options  that  allows  the
2271       caller  to  force  a  particular  socket domain (e.g. IPv6 only or IPv4
2272       only) or a particular socket type (e.g. TCP only or UDP only).
2273
2274
2275       type name_info = {
2276        ni_hostname : string ;  (* Name or IP address of host
2277        *)
2278        ni_service : string ;  (* Name of service or port number
2279        *)
2280        }
2281
2282
2283       Host and service information returned by Unix.getnameinfo .
2284
2285
2286       type getnameinfo_option =
2287        | NI_NOFQDN  (* Do not qualify local host names
2288        *)
2289        | NI_NUMERICHOST  (* Always return host as IP address
2290        *)
2291        | NI_NAMEREQD  (* Fail if host name cannot be determined
2292        *)
2293        | NI_NUMERICSERV  (* Always return service as port number
2294        *)
2295        | NI_DGRAM  (* Consider  the  service  as  UDP-based  instead  of  the
2296       default TCP
2297        *)
2298
2299
2300       Options to Unix.getnameinfo .
2301
2302
2303
2304       val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
2305
2306
2307       getnameinfo  addr  opts  returns  the host name and service name corre‐
2308       sponding to the socket address addr .  opts is a possibly empty list of
2309       options that governs how these names are obtained.
2310
2311
2312       Raises Not_found if an error occurs.
2313
2314
2315
2316
2317       === Terminal interface ===
2318
2319
2320       ===  The  following  functions  implement  the  POSIX standard terminal
2321       interface. They provide control over asynchronous  communication  ports
2322       and  pseudo-terminals.  Refer  to  the  termios man page for a complete
2323       description. ===
2324
2325
2326       type terminal_io = {
2327
2328       mutable c_ignbrk : bool ;  (* Ignore the break condition.
2329        *)
2330
2331       mutable c_brkint : bool ;  (* Signal interrupt on break condition.
2332        *)
2333
2334       mutable c_ignpar : bool ;  (* Ignore characters with parity errors.
2335        *)
2336
2337       mutable c_parmrk : bool ;  (* Mark parity errors.
2338        *)
2339
2340       mutable c_inpck : bool ;  (* Enable parity check on input.
2341        *)
2342
2343       mutable c_istrip : bool ;  (* Strip 8th bit on input characters.
2344        *)
2345
2346       mutable c_inlcr : bool ;  (* Map NL to CR on input.
2347        *)
2348
2349       mutable c_igncr : bool ;  (* Ignore CR on input.
2350        *)
2351
2352       mutable c_icrnl : bool ;  (* Map CR to NL on input.
2353        *)
2354
2355       mutable c_ixon : bool ;  (* Recognize XON/XOFF characters on input.
2356        *)
2357
2358       mutable c_ixoff : bool ;  (* Emit XON/XOFF chars to control input flow.
2359        *)
2360
2361       mutable c_opost : bool ;  (* Enable output processing.
2362        *)
2363
2364       mutable c_obaud : int ;  (* Output baud rate  (0  means  close  connec‐
2365       tion).
2366        *)
2367
2368       mutable c_ibaud : int ;  (* Input baud rate.
2369        *)
2370
2371       mutable c_csize : int ;  (* Number of bits per character (5-8).
2372        *)
2373
2374       mutable c_cstopb : int ;  (* Number of stop bits (1-2).
2375        *)
2376
2377       mutable c_cread : bool ;  (* Reception is enabled.
2378        *)
2379
2380       mutable c_parenb : bool ;  (* Enable parity generation and detection.
2381        *)
2382
2383       mutable c_parodd : bool ;  (* Specify odd parity instead of even.
2384        *)
2385
2386       mutable c_hupcl : bool ;  (* Hang up on last close.
2387        *)
2388
2389       mutable c_clocal : bool ;  (* Ignore modem status lines.
2390        *)
2391
2392       mutable c_isig : bool ;  (* Generate signal on INTR, QUIT, SUSP.
2393        *)
2394
2395       mutable c_icanon : bool ;  (* Enable canonical processing (line buffer‐
2396       ing and editing)
2397        *)
2398
2399       mutable c_noflsh : bool ;  (* Disable flush after INTR, QUIT, SUSP.
2400        *)
2401
2402       mutable c_echo : bool ;  (* Echo input characters.
2403        *)
2404
2405       mutable c_echoe : bool ;  (* Echo ERASE (to erase previous character).
2406        *)
2407
2408       mutable c_echok : bool ;  (* Echo KILL (to erase the current line).
2409        *)
2410
2411       mutable c_echonl : bool ;  (* Echo NL even if c_echo is not set.
2412        *)
2413
2414       mutable c_vintr : char ;  (* Interrupt character (usually ctrl-C).
2415        *)
2416
2417       mutable c_vquit : char ;  (* Quit character (usually ctrl-\).
2418        *)
2419
2420       mutable c_verase : char ;  (* Erase character (usually DEL or ctrl-H).
2421        *)
2422
2423       mutable c_vkill : char ;  (* Kill line character (usually ctrl-U).
2424        *)
2425
2426       mutable c_veof : char ;  (* End-of-file character (usually ctrl-D).
2427        *)
2428
2429       mutable c_veol : char ;  (* Alternate end-of-line char. (usually none).
2430        *)
2431
2432       mutable c_vmin : int ;  (* Minimum number of characters to read  before
2433       the read request is satisfied.
2434        *)
2435
2436       mutable c_vtime : int ;  (* Maximum read wait (in 0.1s units).
2437        *)
2438
2439       mutable c_vstart : char ;  (* Start character (usually ctrl-Q).
2440        *)
2441
2442       mutable c_vstop : char ;  (* Stop character (usually ctrl-S).
2443        *)
2444        }
2445
2446
2447
2448
2449
2450       val tcgetattr : file_descr -> terminal_io
2451
2452       Return  the  status  of  the  terminal  referred  to  by the given file
2453       descriptor.  On Windows, not implemented.
2454
2455
2456       type setattr_when =
2457        | TCSANOW
2458        | TCSADRAIN
2459        | TCSAFLUSH
2460
2461
2462
2463
2464
2465       val tcsetattr : file_descr -> setattr_when -> terminal_io -> unit
2466
2467       Set the status of the terminal referred to by the given  file  descrip‐
2468       tor.  The second argument indicates when the status change takes place:
2469       immediately ( TCSANOW ), when all pending output has been transmitted (
2470       TCSADRAIN ), or after flushing all input that has been received but not
2471       read ( TCSAFLUSH ).  TCSADRAIN is recommended when changing the  output
2472       parameters; TCSAFLUSH , when changing the input parameters.
2473
2474       On Windows, not implemented.
2475
2476
2477
2478       val tcsendbreak : file_descr -> int -> unit
2479
2480       Send  a break condition on the given file descriptor.  The second argu‐
2481       ment is the duration of the break, in  0.1s  units;  0  means  standard
2482       duration (0.25s).
2483
2484       On Windows, not implemented.
2485
2486
2487
2488       val tcdrain : file_descr -> unit
2489
2490       Waits  until  all  output written on the given file descriptor has been
2491       transmitted.
2492
2493       On Windows, not implemented.
2494
2495
2496       type flush_queue =
2497        | TCIFLUSH
2498        | TCOFLUSH
2499        | TCIOFLUSH
2500
2501
2502
2503
2504
2505       val tcflush : file_descr -> flush_queue -> unit
2506
2507       Discard data written on the given file descriptor but not yet transmit‐
2508       ted,  or  data received but not yet read, depending on the second argu‐
2509       ment: TCIFLUSH flushes data received but  not  read,  TCOFLUSH  flushes
2510       data written but not transmitted, and TCIOFLUSH flushes both.
2511
2512       On Windows, not implemented.
2513
2514
2515       type flow_action =
2516        | TCOOFF
2517        | TCOON
2518        | TCIOFF
2519        | TCION
2520
2521
2522
2523
2524
2525       val tcflow : file_descr -> flow_action -> unit
2526
2527       Suspend  or restart reception or transmission of data on the given file
2528       descriptor, depending on the second argument: TCOOFF  suspends  output,
2529       TCOON  restarts  output,  TCIOFF  transmits a STOP character to suspend
2530       input, and TCION transmits a START character to restart input.
2531
2532       On Windows, not implemented.
2533
2534
2535
2536       val setsid : unit -> int
2537
2538       Put the calling process in a new session and detach it  from  its  con‐
2539       trolling terminal.
2540
2541       On Windows, not implemented.
2542
2543
2544
2545
2546
2547OCamldoc                          2018-07-14                           Unix(3)
Impressum