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