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