text
stringlengths 12
786k
|
---|
type addr_info = { ai_family : socket_domain ; ai_socktype : socket_type ; ai_protocol : int ; ai_addr : sockaddr ; ai_canonname : string } |
type getaddrinfo_option = AI_FAMILY of socket_domain | AI_SOCKTYPE of socket_type | AI_PROTOCOL of int | AI_NUMERICHOST | AI_CANONNAME | AI_PASSIVE : string -> string -> getaddrinfo_option list -> addr_info list = " unix_getaddrinfo " |
let getaddrinfo_emulation node service opts = let opt_socktype = ref None and opt_protocol = ref 0 and opt_passive = ref false in List . iter ( function AI_SOCKTYPE s -> opt_socktype := Some s | AI_PROTOCOL p -> opt_protocol := p | AI_PASSIVE -> opt_passive := true | _ -> ( ) ) opts ; let get_port ty kind = if service = " " then [ ty , 0 ] else try [ ty , int_of_string service ] with Failure _ -> try [ ty , ( getservbyname service kind ) . s_port ] with Not_found -> [ ] in let ports = match ! opt_socktype with | None -> get_port SOCK_STREAM " tcp " @ get_port SOCK_DGRAM " udp " | Some SOCK_STREAM -> get_port SOCK_STREAM " tcp " | Some SOCK_DGRAM -> get_port SOCK_DGRAM " udp " | Some ty -> if service = " " then [ ty , 0 ] else [ ] in let addresses = if node = " " then if List . mem AI_PASSIVE opts then [ inet_addr_any , " 0 . 0 . 0 . 0 " ] else [ inet_addr_loopback , " 127 . 0 . 0 . 1 " ] else try [ inet_addr_of_string node , node ] with Failure _ -> try let he = gethostbyname node in List . map ( fun a -> ( a , he . h_name ) ) ( Array . to_list he . h_addr_list ) with Not_found -> [ ] in List . flatten ( List . map ( fun ( ty , port ) -> List . map ( fun ( addr , name ) -> { ai_family = PF_INET ; ai_socktype = ty ; ai_protocol = ! opt_protocol ; ai_addr = ADDR_INET ( addr , port ) ; ai_canonname = name } ) addresses ) ports ) |
let getaddrinfo node service opts = try List . rev ( getaddrinfo_system node service opts ) with Invalid_argument _ -> getaddrinfo_emulation node service opts |
type name_info = { ni_hostname : string ; ni_service : string } |
type getnameinfo_option = NI_NOFQDN | NI_NUMERICHOST | NI_NAMEREQD | NI_NUMERICSERV | NI_DGRAM : sockaddr -> getnameinfo_option list -> name_info = " unix_getnameinfo " |
let getnameinfo_emulation addr opts = match addr with | ADDR_UNIX f -> { ni_hostname = " " ; ni_service = f } | ADDR_INET ( a , p ) -> let hostname = try if List . mem NI_NUMERICHOST opts then raise Not_found ; ( gethostbyaddr a ) . h_name with Not_found -> if List . mem NI_NAMEREQD opts then raise Not_found ; string_of_inet_addr a in let service = try if List . mem NI_NUMERICSERV opts then raise Not_found ; let kind = if List . mem NI_DGRAM opts then " udp " else " tcp " in ( getservbyport p kind ) . s_name with Not_found -> Int . to_string p in { ni_hostname = hostname ; ni_service = service } |
let getnameinfo addr opts = try getnameinfo_system addr opts with Invalid_argument _ -> getnameinfo_emulation addr opts file_descr -> file_descr -> file_descr -> int = " win_create_process " " win_create_process_native " |
let make_cmdline args = let maybe_quote f = if String . contains f ' ' || String . contains f ' " ' \ || String . contains f ' \ t ' || f = " " then Filename . quote f else f in String . concat " " ( List . map maybe_quote ( Array . to_list args ) ) |
let make_process_env env = Array . iter ( fun s -> if String . contains s ' \ 000 ' then raise ( Unix_error ( EINVAL , " " , s ) ) ) env ; String . concat " \ 000 " ( Array . to_list env ) ^ " \ 000 " |
let create_process prog args fd1 fd2 fd3 = win_create_process prog ( make_cmdline args ) None fd1 fd2 fd3 |
let create_process_env prog args env fd1 fd2 fd3 = win_create_process prog ( make_cmdline args ) ( Some ( make_process_env env ) ) fd1 fd2 fd3 |
type popen_process = Process of in_channel * out_channel | Process_in of in_channel | Process_out of out_channel | Process_full of in_channel * out_channel * in_channel |
let popen_processes = ( Hashtbl . create 7 : ( popen_process , int ) Hashtbl . t ) |
let open_proc prog cmdline optenv proc input output error = let pid = win_create_process prog cmdline optenv input output error in Hashtbl . add popen_processes proc pid |
let open_process_cmdline_in prog cmdline = let ( in_read , in_write ) = pipe ~ cloexec : true ( ) in let inchan = in_channel_of_descr in_read in begin try open_proc prog cmdline None ( Process_in inchan ) stdin in_write stderr with e -> close_in inchan ; close in_write ; raise e end ; close in_write ; inchan |
let open_process_cmdline_out prog cmdline = let ( out_read , out_write ) = pipe ~ cloexec : true ( ) in let outchan = out_channel_of_descr out_write in begin try open_proc prog cmdline None ( Process_out outchan ) out_read stdout stderr with e -> close_out outchan ; close out_read ; raise e end ; close out_read ; outchan |
let open_process_cmdline prog cmdline = let ( in_read , in_write ) = pipe ~ cloexec : true ( ) in let ( out_read , out_write ) = try pipe ~ cloexec : true ( ) with e -> close in_read ; close in_write ; raise e in let inchan = in_channel_of_descr in_read in let outchan = out_channel_of_descr out_write in begin try open_proc prog cmdline None ( Process ( inchan , outchan ) ) out_read in_write stderr with e -> close out_read ; close out_write ; close in_read ; close in_write ; raise e end ; close out_read ; close in_write ; ( inchan , outchan ) |
let open_process_cmdline_full prog cmdline env = let ( in_read , in_write ) = pipe ~ cloexec : true ( ) in let ( out_read , out_write ) = try pipe ~ cloexec : true ( ) with e -> close in_read ; close in_write ; raise e in let ( err_read , err_write ) = try pipe ~ cloexec : true ( ) with e -> close in_read ; close in_write ; close out_read ; close out_write ; raise e in let inchan = in_channel_of_descr in_read in let outchan = out_channel_of_descr out_write in let errchan = in_channel_of_descr err_read in begin try open_proc prog cmdline ( Some ( make_process_env env ) ) ( Process_full ( inchan , outchan , errchan ) ) out_read in_write err_write with e -> close out_read ; close out_write ; close in_read ; close in_write ; close err_read ; close err_write ; raise e end ; close out_read ; close in_write ; close err_write ; ( inchan , outchan , errchan ) |
let open_process_args_in prog args = open_process_cmdline_in prog ( make_cmdline args ) |
let open_process_args_out prog args = open_process_cmdline_out prog ( make_cmdline args ) |
let open_process_args prog args = open_process_cmdline prog ( make_cmdline args ) |
let open_process_args_full prog args = open_process_cmdline_full prog ( make_cmdline args ) |
let open_process_shell fn cmd = let shell = try Sys . getenv " COMSPEC " with Not_found -> raise ( Unix_error ( ENOEXEC , " open_process_shell " , cmd ) ) in fn shell ( shell ^ " / c " ^ cmd ) |
let open_process_in cmd = open_process_shell open_process_cmdline_in cmd |
let open_process_out cmd = open_process_shell open_process_cmdline_out cmd |
let open_process cmd = open_process_shell open_process_cmdline cmd |
let open_process_full cmd = open_process_shell open_process_cmdline_full cmd |
let find_proc_id fun_name proc = try Hashtbl . find popen_processes proc with Not_found -> raise ( Unix_error ( EBADF , fun_name , " " ) ) |
let remove_proc_id proc = Hashtbl . remove popen_processes proc |
let process_in_pid inchan = find_proc_id " process_in_pid " ( Process_in inchan ) |
let process_out_pid outchan = find_proc_id " process_out_pid " ( Process_out outchan ) |
let process_pid ( inchan , outchan ) = find_proc_id " process_pid " ( Process ( inchan , outchan ) ) |
let process_full_pid ( inchan , outchan , errchan ) = find_proc_id " process_full_pid " ( Process_full ( inchan , outchan , errchan ) ) |
let close_process_in inchan = let proc = Process_in inchan in let pid = find_proc_id " close_process_in " proc in remove_proc_id proc ; close_in inchan ; snd ( waitpid [ ] pid ) |
let close_process_out outchan = let proc = Process_out outchan in let pid = find_proc_id " close_process_out " proc in remove_proc_id proc ; close_out outchan ; snd ( waitpid [ ] pid ) |
let close_process ( inchan , outchan ) = let proc = Process ( inchan , outchan ) in let pid = find_proc_id " close_process " proc in remove_proc_id proc ; close_in inchan ; close_out outchan ; snd ( waitpid [ ] pid ) |
let close_process_full ( inchan , outchan , errchan ) = let proc = Process_full ( inchan , outchan , errchan ) in let pid = find_proc_id " close_process_full " proc in remove_proc_id proc ; close_in inchan ; close_out outchan ; close_in errchan ; snd ( waitpid [ ] pid ) file_descr list -> file_descr list -> file_descr list -> float -> file_descr list * file_descr list * file_descr list = " unix_select " |
let open_connection sockaddr = let sock = socket ~ cloexec : true ( domain_of_sockaddr sockaddr ) SOCK_STREAM 0 in try connect sock sockaddr ; ( in_channel_of_descr sock , out_channel_of_descr sock ) with exn -> close sock ; raise exn |
let shutdown_connection inchan = shutdown ( descr_of_in_channel inchan ) SHUTDOWN_SEND |
let establish_server _server_fun _sockaddr = invalid_arg " Unix . establish_server not implemented " |
type terminal_io = { mutable c_ignbrk : bool ; mutable c_brkint : bool ; mutable c_ignpar : bool ; mutable c_parmrk : bool ; mutable c_inpck : bool ; mutable c_istrip : bool ; mutable c_inlcr : bool ; mutable c_igncr : bool ; mutable c_icrnl : bool ; mutable c_ixon : bool ; mutable c_ixoff : bool ; mutable c_opost : bool ; mutable c_obaud : int ; mutable c_ibaud : int ; mutable c_csize : int ; mutable c_cstopb : int ; mutable c_cread : bool ; mutable c_parenb : bool ; mutable c_parodd : bool ; mutable c_hupcl : bool ; mutable c_clocal : bool ; mutable c_isig : bool ; mutable c_icanon : bool ; mutable c_noflsh : bool ; mutable c_echo : bool ; mutable c_echoe : bool ; mutable c_echok : bool ; mutable c_echonl : bool ; mutable c_vintr : char ; mutable c_vquit : char ; mutable c_verase : char ; mutable c_vkill : char ; mutable c_veof : char ; mutable c_veol : char ; mutable c_vmin : int ; mutable c_vtime : int ; mutable c_vstart : char ; mutable c_vstop : char } |
type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH |
let tcgetattr _fd = invalid_arg " Unix . tcgetattr not implemented " |
let tcsetattr _fd _wh = invalid_arg " Unix . tcsetattr not implemented " |
let tcsendbreak _fd _n = invalid_arg " Unix . tcsendbreak not implemented " |
let tcdrain _fd = invalid_arg " Unix . tcdrain not implemented " |
type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH |
let tcflush _fd _q = invalid_arg " Unix . tcflush not implemented " |
type flow_action = TCOOFF | TCOON | TCIOFF | TCION |
let tcflow _fd _fl = invalid_arg " Unix . tcflow not implemented " |
let setsid ( ) = invalid_arg " Unix . setsid not implemented " |
let unlink_safe file = try Unix . unlink file with _ -> ( ) |
let mkdir_safe dir perm = try Unix . mkdir dir perm with Unix . Unix_error ( Unix . EEXIST , _ , _ ) -> ( ) |
let mkdir_rec dir perm = let rec p_mkdir dir = let p_name = Filename . dirname dir in if p_name <> " " / && p_name <> " . " then p_mkdir p_name ; mkdir_safe dir perm in p_mkdir dir |
let pidfile_write filename = let fd = Unix . openfile filename [ Unix . O_WRONLY ; Unix . O_CREAT ; Unix . O_TRUNC ; ] 0o640 in finally ( fun ( ) -> let pid = Unix . getpid ( ) in let buf = string_of_int pid ^ " \ n " in let len = String . length buf in if Unix . write fd ( Bytes . unsafe_of_string buf ) 0 len <> len then failwith " pidfile_write failed " ; ) ( fun ( ) -> Unix . close fd ) |
let pidfile_read filename = let fd = Unix . openfile filename [ Unix . O_RDONLY ] 0o640 in finally ( fun ( ) -> try let buf = Bytes . create 80 in let rd = Unix . read fd buf 0 ( Bytes . length buf ) in if rd = 0 then failwith " pidfile_read failed " ; Scanf . sscanf ( Bytes . sub_string buf 0 rd ) " % d " ( fun i -> Some i ) with _ -> None ) ( fun ( ) -> Unix . close fd ) |
let with_file file mode perms f = let fd = Unix . openfile file mode perms in Xapi_stdext_pervasives . Pervasiveext . finally ( fun ( ) -> f fd ) ( fun ( ) -> Unix . close fd ) |
let daemonize ( ) = match Unix . fork ( ) with | 0 -> if Unix . setsid ( ) == - 1 then failwith " Unix . setsid failed " ; begin match Unix . fork ( ) with | 0 -> with_file " / dev / null " [ Unix . O_WRONLY ] 0 ( fun nullfd -> Unix . close Unix . stdin ; Unix . dup2 nullfd Unix . stdout ; Unix . dup2 nullfd Unix . stderr ) | _ -> exit 0 end | _ -> exit 0 |
let lines_fold f start input = let accumulator = ref start in let running = ref true in while ! running do let line = try Some ( input_line input ) with End_of_file -> None in match line with | Some line -> begin try accumulator := ( f ! accumulator line ) with Break -> running := false end | None -> running := false done ; ! accumulator |
let lines_iter f = lines_fold ( fun ( ) line -> ignore ( f line ) ) ( ) |
let with_input_channel file f = let input = open_in file in finally ( fun ( ) -> f input ) ( fun ( ) -> close_in input ) |
let file_lines_fold f start file_path = with_input_channel file_path ( lines_fold f start ) |
let read_lines ( ~ path : string ) : string list = List . rev ( file_lines_fold ( fun acc line -> line :: acc ) [ ] path ) |
let file_lines_iter f = file_lines_fold ( fun ( ) line -> ignore ( f line ) ) ( ) |
let fd_blocks_fold block_size f start fd = let block = Bytes . create block_size in let rec fold acc = let n = Unix . read fd block 0 block_size in let b = if n = block_size then block else Bytes . sub block 0 n in if n = 0 then acc else fold ( f acc b ) in fold start |
let with_directory dir f = let dh = Unix . opendir dir in Xapi_stdext_pervasives . Pervasiveext . finally ( fun ( ) -> f dh ) ( fun ( ) -> Unix . closedir dh ) |
let buffer_of_fd fd = fd_blocks_fold 1024 ( fun b s -> Buffer . add_bytes b s ; b ) ( Buffer . create 1024 ) fd |
let string_of_fd fd = Buffer . contents ( buffer_of_fd fd ) |
let buffer_of_file file_path = with_file file_path [ Unix . O_RDONLY ] 0 buffer_of_fd |
let string_of_file file_path = Buffer . contents ( buffer_of_file file_path ) |
let atomic_write_to_file fname perms f = let dir_path = Filename . dirname fname in let tmp_path , tmp_chan = Filename . open_temp_file ~ temp_dir : dir_path " " " . tmp " in let tmp_fd = Unix . descr_of_out_channel tmp_chan in let write_tmp_file ( ) = let result = f tmp_fd in Unix . fchmod tmp_fd perms ; Unix . fsync tmp_fd ; result in let write_and_persist ( ) = let result = finally write_tmp_file ( fun ( ) -> Stdlib . close_out tmp_chan ) in Unix . rename tmp_path fname ; let dir_fd = Unix . openfile dir_path [ O_RDONLY ] 0 in finally ( fun ( ) -> Unix . fsync dir_fd ) ( fun ( ) -> Unix . close dir_fd ) ; result in finally write_and_persist ( fun ( ) -> unlink_safe tmp_path ) |
let write_bytes_to_file fname b = atomic_write_to_file fname 0o644 ( fun fd -> let len = Bytes . length b in let written = Unix . write fd b 0 len in if written <> len then ( failwith " Short write occured " ) ) ! |
let write_string_to_file fname s = write_bytes_to_file fname ( Bytes . unsafe_of_string s ) |
let execv_get_output cmd args = let ( pipe_exit , pipe_entrance ) = Unix . pipe ( ) in let r = try Unix . set_close_on_exec pipe_exit ; true with _ -> false in match Unix . fork ( ) with | 0 -> Unix . dup2 pipe_entrance Unix . stdout ; Unix . close pipe_entrance ; if not r then Unix . close pipe_exit ; begin try Unix . execv cmd args with _ -> exit 127 end | pid -> Unix . close pipe_entrance ; pid , pipe_exit |
let copy_file_internal ? limit reader writer = let buffer = Bytes . make 65536 ' \ 000 ' in let buffer_len = Int64 . of_int ( Bytes . length buffer ) in let finished = ref false in let total_bytes = ref 0L in let limit = ref limit in while not ( ! finished ) do let requested = min ( Option . value ~ default : buffer_len ! limit ) buffer_len in let num = reader buffer 0 ( Int64 . to_int requested ) in let num64 = Int64 . of_int num in limit := Option . map ( fun x -> Int64 . sub x num64 ) ! limit ; ignore_int ( writer buffer 0 num ) ; total_bytes := Int64 . add ! total_bytes num64 ; finished := num = 0 || ! limit = Some 0L ; done ; ! total_bytes |
let copy_file ? limit ifd ofd = copy_file_internal ? limit ( Unix . read ifd ) ( Unix . write ofd ) |
let file_exists file_path = try Unix . access file_path [ Unix . F_OK ] ; true with _ -> false |
let touch_file file_path = let fd = Unix . openfile file_path [ Unix . O_WRONLY ; Unix . O_CREAT ; Unix . O_NOCTTY ; Unix . O_NONBLOCK ] 0o666 in Unix . close fd ; Unix . utimes file_path 0 . 0 0 . 0 |
let is_empty_file file_path = try let stats = Unix . stat file_path in stats . Unix . st_size = 0 with Unix . Unix_error ( Unix . ENOENT , _ , _ ) -> false |
let delete_empty_file file_path = if is_empty_file file_path then ( Sys . remove file_path ; true ) else ( false ) |
let open_connection_fd host port = let open Unix in let addrinfo = getaddrinfo host ( string_of_int port ) [ AI_SOCKTYPE SOCK_STREAM ] in match addrinfo with | [ ] -> failwith ( Printf . sprintf " Couldn ' t resolve hostname : % s " host ) | ai :: _ -> let s = socket ai . ai_family ai . ai_socktype 0 in try connect s ai . ai_addr ; s with e -> Backtrace . is_important e ; close s ; raise e |
let open_connection_unix_fd filename = let s = Unix . socket Unix . PF_UNIX Unix . SOCK_STREAM 0 in try let addr = Unix . ADDR_UNIX ( filename ) in Unix . connect s addr ; s with e -> Backtrace . is_important e ; Unix . close s ; raise e |
module CBuf = struct type t = { mutable buffer : bytes ; mutable len : int ; mutable start : int ; mutable r_closed : bool ; mutable w_closed : bool ; } let empty length = { buffer = Bytes . create length ; len = 0 ; start = 0 ; r_closed = false ; w_closed = false ; } let drop ( x : t ) n = if n > x . len then failwith ( Printf . sprintf " drop % d > % d " n x . len ) ; x . start <- ( x . start + n ) mod ( Bytes . length x . buffer ) ; x . len <- x . len - n let should_read ( x : t ) = not x . r_closed && ( x . len < ( Bytes . length x . buffer - 1 ) ) let should_write ( x : t ) = not x . w_closed && ( x . len > 0 ) let end_of_reads ( x : t ) = x . r_closed && x . len = 0 let end_of_writes ( x : t ) = x . w_closed let write ( x : t ) fd = let next = min ( Bytes . length x . buffer ) ( x . start + x . len ) in let len = next - x . start in let written = try Unix . single_write fd x . buffer x . start len with _ -> x . w_closed <- true ; len in drop x written let read ( x : t ) fd = let next = ( x . start + x . len ) mod ( Bytes . length x . buffer ) in let len = min ( Bytes . length x . buffer - next ) ( Bytes . length x . buffer - x . len ) in let read = Unix . read fd x . buffer next len in if read = 0 then x . r_closed <- true ; x . len <- x . len + read end |
let kill_and_wait ( ? signal = Sys . sigterm ) ( ? timeout = 10 . ) pid = let proc_entry_exists pid = try Unix . access ( Printf . sprintf " / proc /% d " pid ) [ Unix . F_OK ] ; true with _ -> false in if pid > 0 && proc_entry_exists pid then ( let loop_time_waiting = 0 . 03 in let left = ref timeout in let readcmdline pid = try string_of_file ( Printf . sprintf " / proc /% d / cmdline " pid ) with _ -> " " in let reference = readcmdline pid and quit = ref false in Unix . kill pid signal ; while proc_entry_exists pid && not ! quit && ! left > 0 . do let cmdline = readcmdline pid in if cmdline = reference then ( ignore ( Unix . select [ ] [ ] [ ] loop_time_waiting ) ; left := ! left . - loop_time_waiting ) else ( quit := true ) done ; if ! left <= 0 . then raise Process_still_alive ; ) |
let string_of_signal x = let table = [ Sys . sigabrt , " SIGABRT " ; Sys . sigalrm , " SIGALRM " ; Sys . sigfpe , " SIGFPE " ; Sys . sighup , " SIGHUP " ; Sys . sigill , " SIGILL " ; Sys . sigint , " SIGINT " ; Sys . sigkill , " SIGKILL " ; Sys . sigpipe , " SIGPIPE " ; Sys . sigquit , " SIGQUIT " ; Sys . sigsegv , " SIGSEGV " ; Sys . sigterm , " SIGTERM " ; Sys . sigusr1 , " SIGUSR1 " ; Sys . sigusr2 , " SIGUSR2 " ; Sys . sigchld , " SIGCHLD " ; Sys . sigcont , " SIGCONT " ; Sys . sigstop , " SIGSTOP " ; Sys . sigttin , " SIGTTIN " ; Sys . sigttou , " SIGTTOU " ; Sys . sigvtalrm , " SIGVTALRM " ; Sys . sigprof , " SIGPROF " ; ] in if List . mem_assoc x table then List . assoc x table else ( Printf . sprintf " ( ocaml signal % d with an unknown name ) " x ) |
let proxy ( a : Unix . file_descr ) ( b : Unix . file_descr ) = let size = 64 * 1024 in let a ' = CBuf . empty size and b ' = CBuf . empty size in Unix . set_nonblock a ; Unix . set_nonblock b ; try while true do let r = ( if CBuf . should_read a ' then [ a ] else [ ] ) @ ( if CBuf . should_read b ' then [ b ] else [ ] ) in let w = ( if CBuf . should_write a ' then [ b ] else [ ] ) @ ( if CBuf . should_write b ' then [ a ] else [ ] ) in if r = [ ] && w = [ ] then raise End_of_file ; let r , w , _ = Unix . select r w [ ] ( - 1 . 0 ) in List . iter ( fun fd -> if a = fd then CBuf . write b ' a else CBuf . write a ' b ) w ; List . iter ( fun fd -> if a = fd then CBuf . read a ' a else CBuf . read b ' b ) r ; List . iter ( fun ( buf , fd ) -> if CBuf . end_of_reads buf then Unix . shutdown fd Unix . SHUTDOWN_SEND ; if CBuf . end_of_writes buf then Unix . shutdown fd Unix . SHUTDOWN_RECEIVE ) [ a ' , b ; b ' , a ] done with _ -> ( try Unix . clear_nonblock a with _ -> ( ) ) ; ( try Unix . clear_nonblock b with _ -> ( ) ) ; ( try Unix . close a with _ -> ( ) ) ; ( try Unix . close b with _ -> ( ) ) |
let rec really_read fd string off n = if n = 0 then ( ) else let m = Unix . read fd string off n in if m = 0 then raise End_of_file ; really_read fd string ( off + m ) ( n - m ) |
let really_read_string fd length = let buf = Bytes . make length ' \ 000 ' in really_read fd buf 0 length ; Bytes . unsafe_to_string buf |
let try_read_string ? limit fd = let buf = Buffer . create 0 in let chunk = match limit with None -> 4096 | Some x -> x in let cache = Bytes . make chunk ' \ 000 ' in let finished = ref false in while not ! finished do let to_read = match limit with | Some x -> min ( x - ( Buffer . length buf ) ) chunk | None -> chunk in let read_bytes = Unix . read fd cache 0 to_read in Buffer . add_subbytes buf cache 0 read_bytes ; if read_bytes = 0 then finished := true done ; Buffer . contents buf |
let rec restart_on_EINTR f x = try f x with Unix . Unix_error ( Unix . EINTR , _ , _ ) -> restart_on_EINTR f x let n = restart_on_EINTR ( Unix . single_write_substring fd buffer offset ) len in if n < len then really_write fd buffer ( offset + n ) ( len - n ) ; ; |
let really_write_string fd string = really_write fd string 0 ( String . length string ) |
let time_limited_write_internal ( write : Unix . file_descr -> ' a -> int -> int -> int ) filedesc length data target_response_time = let total_bytes_to_write = length in let bytes_written = ref 0 in let now = ref ( Unix . gettimeofday ( ) ) in while ! bytes_written < total_bytes_to_write && ! now < target_response_time do let remaining_time = target_response_time . - ! now in let ( _ , ready_to_write , _ ) = Unix . select [ ] [ filedesc ] [ ] remaining_time in if List . mem filedesc ready_to_write then begin let bytes_to_write = total_bytes_to_write - ! bytes_written in let bytes = ( try write filedesc data ! bytes_written bytes_to_write with Unix . Unix_error ( Unix . EAGAIN , _ , _ ) | Unix . Unix_error ( Unix . EWOULDBLOCK , _ , _ ) -> 0 ) in bytes_written := bytes + ! bytes_written ; end ; now := Unix . gettimeofday ( ) done ; if ! bytes_written = total_bytes_to_write then ( ) else raise Timeout |
let time_limited_write filedesc length data target_response_time = time_limited_write_internal Unix . write filedesc length data target_response_time |
let time_limited_write_substring filedesc length data target_response_time = time_limited_write_internal Unix . write_substring filedesc length data target_response_time |
let time_limited_read filedesc length target_response_time = let total_bytes_to_read = length in let bytes_read = ref 0 in let buf = Bytes . make total_bytes_to_read ' \ 000 ' in let now = ref ( Unix . gettimeofday ( ) ) in while ! bytes_read < total_bytes_to_read && ! now < target_response_time do let remaining_time = target_response_time . - ! now in let ( ready_to_read , _ , _ ) = Unix . select [ filedesc ] [ ] [ ] remaining_time in if List . mem filedesc ready_to_read then begin let bytes_to_read = total_bytes_to_read - ! bytes_read in let bytes = ( try Unix . read filedesc buf ! bytes_read bytes_to_read with Unix . Unix_error ( Unix . EAGAIN , _ , _ ) | Unix . Unix_error ( Unix . EWOULDBLOCK , _ , _ ) -> 0 ) in if bytes = 0 then raise End_of_file else bytes_read := bytes + ! bytes_read end ; now := Unix . gettimeofday ( ) done ; if ! bytes_read = total_bytes_to_read then ( Bytes . unsafe_to_string buf ) else raise Timeout |
let read_data_in_chunks_internal ( sub : bytes -> int -> int -> ' a ) ( f : ' a -> int -> unit ) ( ? block_size = 1024 ) ( ? max_bytes = - 1 ) from_fd = let buf = Bytes . make block_size ' \ 000 ' in let rec do_read acc = let remaining_bytes = max_bytes - acc in if remaining_bytes = 0 then acc else begin let bytes_to_read = ( if max_bytes < 0 || remaining_bytes > block_size then block_size else remaining_bytes ) in let bytes_read = Unix . read from_fd buf 0 bytes_to_read in if bytes_read = 0 then acc else begin f ( sub buf 0 bytes_read ) bytes_read ; do_read ( acc + bytes_read ) end end in do_read 0 |
let read_data_in_string_chunks ( f : string -> int -> unit ) ( ? block_size = 1024 ) ( ? max_bytes = - 1 ) from_fd = read_data_in_chunks_internal Bytes . sub_string f ~ block_size ~ max_bytes from_fd |
let read_data_in_chunks ( f : bytes -> int -> unit ) ( ? block_size = 1024 ) ( ? max_bytes = - 1 ) from_fd = read_data_in_chunks_internal Bytes . sub f ~ block_size ~ max_bytes from_fd |
let spawnvp ( ? pid_callback ( = fun _ -> ( ) ) ) cmd args = match Unix . fork ( ) with | 0 -> Unix . execvp cmd args | pid -> begin try pid_callback pid with _ -> ( ) end ; snd ( Unix . waitpid [ ] pid ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.