1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2000-2017, University of Amsterdam 7 VU University Amsterdam 8 All rights reserved. 9 10 Redistribution and use in source and binary forms, with or without 11 modification, are permitted provided that the following conditions 12 are met: 13 14 1. Redistributions of source code must retain the above copyright 15 notice, this list of conditions and the following disclaimer. 16 17 2. Redistributions in binary form must reproduce the above copyright 18 notice, this list of conditions and the following disclaimer in 19 the documentation and/or other materials provided with the 20 distribution. 21 22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 25 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 26 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 27 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 28 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 30 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 32 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 33 POSSIBILITY OF SUCH DAMAGE. 34*/ 35 36:- module(unix, 37 [ fork/1, % -'client'|pid 38 exec/1, % +Command(...Args...) 39 fork_exec/1, % +Command(...Args...) 40 wait/2, % -Pid, -Reason 41 kill/2, % +Pid. +Signal 42 pipe/2, % +Read, +Write 43 dup/2, % +From, +To 44 detach_IO/0, 45 detach_IO/1, % +Stream 46 environ/1 % -[Name=Value] 47 ]). 48:- use_module(library(shlib)). 49 50/** <module> Unix specific operations 51 52The library(unix) library provides the commonly used Unix primitives to 53deal with process management. These primitives are useful for many 54tasks, including server management, parallel computation, exploiting and 55controlling other processes, etc. 56 57The predicates in this library are modelled closely after their native 58Unix counterparts. 59 60@see library(process) provides a portable high level interface to create 61and manage processes. 62*/ 63 64:- use_foreign_library(foreign(unix), install_unix). 65 66%! fork(-Pid) is det. 67% 68% Clone the current process into two branches. In the child, Pid 69% is unified to child. In the original process, Pid is unified to 70% the process identifier of the created child. Both parent and 71% child are fully functional Prolog processes running the same 72% program. The processes share open I/O streams that refer to Unix 73% native streams, such as files, sockets and pipes. Data is not 74% shared, though on most Unix systems data is initially shared and 75% duplicated only if one of the programs attempts to modify the 76% data. 77% 78% Unix fork() is the only way to create new processes and fork/1 79% is a simple direct interface to it. 80% 81% @error permission_error(fork, process, main) is raised if 82% the calling thread is not the only thread in the 83% process. Forking a Prolog process with threads 84% will typically deadlock because only the calling 85% thread is cloned in the fork, while all thread 86% synchronization are cloned. 87 88fork(Pid) :- 89 fork_warn_threads, 90 fork_(Pid). 91 92%! fork_warn_threads 93% 94% See whether we are the only thread. If not, we cannot fork 95 96fork_warn_threads :- 97 set_prolog_gc_thread(stop), 98 findall(T, other_thread(T), Others), 99 ( Others == [] 100 -> true 101 ; throw(error(permission_error(fork, process, main), 102 context(_, running_threads(Others)))) 103 ). 104 105:- if(\+current_predicate(set_prolog_gc_thread/1)). 106set_prolog_gc_thread(stop) :- 107 ( catch(thread_signal(gc, abort), 108 error(existence_error(thread, _), _), 109 fail) 110 -> thread_join(gc) 111 ; true 112 ). 113:- endif. 114 115other_thread(T) :- 116 thread_self(Me), 117 thread_property(T, status(Status)), 118 T \== Me, 119 ( Status == running 120 -> true 121 ; print_message(warning, fork(join(T, Status))), 122 thread_join(T, _), 123 fail 124 ). 125 126%! fork_exec(+Command) is det. 127% 128% Fork (as fork/1) and exec (using exec/1) the child immediately. 129% This behaves as the code below, but bypasses the check for the 130% existence of other threads because this is a safe scenario. 131% 132% == 133% fork_exec(Command) :- 134% ( fork(child) 135% -> exec(Command) 136% ; true 137% ). 138% == 139 140fork_exec(Command) :- 141 ( fork_(child) 142 -> exec(Command) 143 ; true 144 ). 145 146%! exec(+Command) 147% 148% Replace the running program by starting Command. Command is a 149% callable term. The functor is the command and the arguments 150% provide the command-line arguments for the command. Each 151% command-line argument must be atomic and is converted to a 152% string before passed to the Unix call execvp(). Here are some 153% examples: 154% 155% - exec(ls('-l')) 156% - exec('/bin/ls'('-l', '/home/jan')) 157% 158% Unix exec() is the only way to start an executable file 159% executing. It is commonly used together with fork/1. For example 160% to start netscape on an URL in the background, do: 161% 162% == 163% run_netscape(URL) :- 164% ( fork(child), 165% exec(netscape(URL)) 166% ; true 167% ). 168% == 169% 170% Using this code, netscape remains part of the process-group of 171% the invoking Prolog process and Prolog does not wait for 172% netscape to terminate. The predicate wait/2 allows waiting for a 173% child, while detach_IO/0 disconnects the child as a deamon 174% process. 175 176%! wait(?Pid, -Status) is det. 177% 178% Wait for a child to change status. Then report the child that 179% changed status as well as the reason. If Pid is bound on entry 180% then the status of the specified child is reported. If not, then 181% the status of any child is reported. Status is unified with 182% exited(ExitCode) if the child with pid Pid was terminated by 183% calling exit() (Prolog halt/1). ExitCode is the return status. 184% Status is unified with signaled(Signal) if the child died due to 185% a software interrupt (see kill/2). Signal contains the signal 186% number. Finally, if the process suspended execution due to a 187% signal, Status is unified with stopped(Signal). 188 189%! kill(+Pid, +Signal) is det. 190% 191% Deliver a software interrupt to the process with identifier Pid 192% using software-interrupt number Signal. See also on_signal/2. 193% Signals can be specified as an integer or signal name, where 194% signal names are derived from the C constant by dropping the 195% =SIG= prefix and mapping to lowercase. E.g. =int= is the same as 196% =SIGINT= in C. The meaning of the signal numbers can be found in 197% the Unix manual. 198 199%! pipe(-InSream, -OutStream) is det. 200% 201% Create a communication-pipe. This is normally used to make a 202% child communicate to its parent. After pipe/2, the process is 203% cloned and, depending on the desired direction, both processes 204% close the end of the pipe they do not use. Then they use the 205% remaining stream to communicate. Here is a simple example: 206% 207% == 208% :- use_module(library(unix)). 209% 210% fork_demo(Result) :- 211% pipe(Read, Write), 212% fork(Pid), 213% ( Pid == child 214% -> close(Read), 215% format(Write, '~q.~n', 216% [hello(world)]), 217% flush_output(Write), 218% halt 219% ; close(Write), 220% read(Read, Result), 221% close(Read) 222% ). 223% == 224 225 226%! dup(+FromStream, +ToStream) is det. 227% 228% Interface to Unix dup2(), copying the underlying filedescriptor 229% and thus making both streams point to the same underlying 230% object. This is normally used together with fork/1 and pipe/2 to 231% talk to an external program that is designed to communicate 232% using standard I/O. 233% 234% Both FromStream and ToStream either refer to a Prolog stream or 235% an integer descriptor number to refer directly to OS 236% descriptors. See also demo/pipe.pl in the source-distribution of 237% this package. 238 239 240%! detach_IO(+Stream) is det. 241% 242% This predicate is intended to create Unix _deamon_ processes. It 243% performs two actions. 244% 245% 1. The I/O streams =user_input=, =user_output= and 246% =user_error= are closed if they are connected to a terminal 247% (see =tty= property in stream_property/2). Input streams are 248% rebound to a dummy stream that returns EOF. Output streams are 249% reboud to forward their output to Stream. 250% 251% 2. The process is detached from the current process-group and 252% its controlling terminal. This is achieved using setsid() if 253% provided or using ioctl() =TIOCNOTTY= on =|/dev/tty|=. 254% 255% To ignore all output, it may be rebound to a null stream. For 256% example: 257% 258% == 259% ..., 260% open_null_stream(Out), 261% detach_IO(Out). 262% == 263% 264% The detach_IO/1 should be called only once per process. 265% Subsequent calls silently succeed without any side effects. 266% 267% @see detach_IO/0 and library(syslog). 268 269%! detach_IO is det. 270% 271% Detach I/O similar to detach_IO/1. The output streams are bound 272% to a file =|/tmp/pl-out.<pid>|=. Output is line buffered (see 273% set_stream/2). 274% 275% @compat Older versions of this predicate only created this file 276% if there was output. 277% @see library(syslog) allows for sending output to the Unix 278% logging service. 279 280detach_IO :- 281 current_prolog_flag(pid, Pid), 282 atom_concat('/tmp/pl-out.', Pid, TmpFile), 283 open(TmpFile, write, Out, [alias(daemon_output)]), 284 set_stream(Out, buffer(line)), 285 detach_IO(Out). 286 287:- if(current_predicate(prctl/1)). 288:- export(prctl/1). 289 290%! prctl(+Option) is det. 291% 292% Access to Linux process control operations. Defines values for 293% Option are: 294% 295% - set_dumpable(+Boolean) 296% Control whether the process is allowed to dump core. This 297% right is dropped under several uid and gid conditions. 298% - get_dumpable(-Boolean) 299% Get the value of the dumpable flag. 300 301:- endif. 302 303:- if(current_predicate(sysconf/1)). 304:- export(sysconf/1). 305 306%! sysconf(+Conf) is semidet. 307% 308% Access system configuration. See sysconf(1) for details. Conf is 309% a term Config(Value), where Value is always an integer. Config 310% is the sysconf() name after removing =_SC_= and conversion to 311% lowercase. Currently support the following configuration info: 312% =arg_max=, =child_max=, =clk_tck=, =open_max=, =pagesize=, 313% =phys_pages=, =avphys_pages=, =nprocessors_conf= and 314% =nprocessors_onln=. Note that not all values may be supported on 315% all operating systems. 316 317:- endif. 318 319 /******************************* 320 * MESSAGES * 321 *******************************/ 322 323:- multifile 324 prolog:message//1. 325 326prologmessage(fork(join(T, Status))) --> 327 [ 'Fork: joining thead ~p (status: ~p)'-[T, Status] ]