View source with raw comments or as raw
   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-2015, 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    findall(T, other_thread(T), Others),
  98    (   Others == []
  99    ->  true
 100    ;   throw(error(permission_error(fork, process, main),
 101                    context(_, running_threads(Others))))
 102    ).
 103
 104other_thread(T) :-
 105    thread_self(Me),
 106    thread_property(T, status(Status)),
 107    T \== Me,
 108    (   Status == running
 109    ->  true
 110    ;   print_message(warning, fork(join(T, Status))),
 111        thread_join(T, _),
 112        fail
 113    ).
 114
 115%!  fork_exec(+Command) is det.
 116%
 117%   Fork (as fork/1) and exec (using  exec/1) the child immediately.
 118%   This behaves as the code below, but   bypasses the check for the
 119%   existence of other threads because this is a safe scenario.
 120%
 121%     ==
 122%     fork_exec(Command) :-
 123%           (   fork(child)
 124%           ->  exec(Command)
 125%           ;   true
 126%           ).
 127%     ==
 128
 129fork_exec(Command) :-
 130    (   fork_(child)
 131    ->  exec(Command)
 132    ;   true
 133    ).
 134
 135%!  exec(+Command)
 136%
 137%   Replace the running program by starting   Command.  Command is a
 138%   callable term. The functor is  the   command  and  the arguments
 139%   provide  the  command-line  arguments  for   the  command.  Each
 140%   command-line argument must be  atomic  and   is  converted  to a
 141%   string before passed to the Unix   call  execvp(). Here are some
 142%   examples:
 143%
 144%     - exec(ls('-l'))
 145%     - exec('/bin/ls'('-l', '/home/jan'))
 146%
 147%   Unix exec() is  the  only  way   to  start  an  executable  file
 148%   executing. It is commonly used together with fork/1. For example
 149%   to start netscape on an URL in the background, do:
 150%
 151%     ==
 152%     run_netscape(URL) :-
 153%             (    fork(child),
 154%                  exec(netscape(URL))
 155%             ;    true
 156%             ).
 157%     ==
 158%
 159%   Using this code, netscape remains part   of the process-group of
 160%   the invoking Prolog  process  and  Prolog   does  not  wait  for
 161%   netscape to terminate. The predicate wait/2 allows waiting for a
 162%   child, while detach_IO/0  disconnects  the   child  as  a deamon
 163%   process.
 164
 165%!  wait(?Pid, -Status) is det.
 166%
 167%   Wait for a child to change status.   Then  report the child that
 168%   changed status as well as the reason.   If Pid is bound on entry
 169%   then the status of the specified child is reported. If not, then
 170%   the status of any child  is   reported.  Status  is unified with
 171%   exited(ExitCode) if the child with  pid   Pid  was terminated by
 172%   calling exit() (Prolog halt/1). ExitCode   is the return status.
 173%   Status is unified with signaled(Signal) if the child died due to
 174%   a software interrupt (see kill/2).   Signal  contains the signal
 175%   number. Finally, if the process  suspended   execution  due to a
 176%   signal, Status is unified with stopped(Signal).
 177
 178%!  kill(+Pid, +Signal) is det.
 179%
 180%   Deliver a software interrupt to the  process with identifier Pid
 181%   using software-interrupt number Signal.   See  also on_signal/2.
 182%   Signals can be specified as  an   integer  or signal name, where
 183%   signal names are derived from  the   C  constant by dropping the
 184%   =SIG= prefix and mapping to lowercase. E.g. =int= is the same as
 185%   =SIGINT= in C. The meaning of the signal numbers can be found in
 186%   the Unix manual.
 187
 188%!  pipe(-InSream, -OutStream) is det.
 189%
 190%   Create a communication-pipe. This is  normally   used  to make a
 191%   child communicate to its parent. After   pipe/2,  the process is
 192%   cloned and, depending on the   desired direction, both processes
 193%   close the end of the pipe they  do   not  use. Then they use the
 194%   remaining stream to communicate. Here is a simple example:
 195%
 196%     ==
 197%     :- use_module(library(unix)).
 198%
 199%     fork_demo(Result) :-
 200%             pipe(Read, Write),
 201%             fork(Pid),
 202%             (   Pid == child
 203%             ->  close(Read),
 204%                 format(Write, '~q.~n',
 205%                        [hello(world)]),
 206%                 flush_output(Write),
 207%                 halt
 208%             ;   close(Write),
 209%                 read(Read, Result),
 210%                 close(Read)
 211%             ).
 212%     ==
 213
 214
 215%!  dup(+FromStream, +ToStream) is det.
 216%
 217%   Interface to Unix dup2(), copying  the underlying filedescriptor
 218%   and thus making both  streams  point   to  the  same  underlying
 219%   object. This is normally used together with fork/1 and pipe/2 to
 220%   talk to an external program  that   is  designed  to communicate
 221%   using standard I/O.
 222%
 223%   Both FromStream and ToStream either refer  to a Prolog stream or
 224%   an  integer  descriptor  number   to    refer   directly  to  OS
 225%   descriptors. See also demo/pipe.pl in the source-distribution of
 226%   this package.
 227
 228
 229%!  detach_IO(+Stream) is det.
 230%
 231%   This predicate is intended to create Unix _deamon_ processes. It
 232%   performs two actions.
 233%
 234%     1. The I/O streams =user_input=, =user_output= and
 235%     =user_error= are closed if they are connected to a terminal
 236%     (see =tty= property in stream_property/2). Input streams are
 237%     rebound to a dummy stream that returns EOF. Output streams are
 238%     reboud to forward their output to Stream.
 239%
 240%     2. The process is detached from the current process-group and
 241%     its controlling terminal. This is achieved using setsid() if
 242%     provided or using ioctl() =TIOCNOTTY= on =|/dev/tty|=.
 243%
 244%   To ignore all output, it may be   rebound  to a null stream. For
 245%   example:
 246%
 247%     ==
 248%           ...,
 249%           open_null_stream(Out),
 250%           detach_IO(Out).
 251%     ==
 252%
 253%   The  detach_IO/1  should  be  called   only  once  per  process.
 254%   Subsequent calls silently succeed without any side effects.
 255%
 256%   @see detach_IO/0 and library(syslog).
 257
 258%!  detach_IO is det.
 259%
 260%   Detach I/O similar to detach_IO/1. The  output streams are bound
 261%   to a file =|/tmp/pl-out.<pid>|=. Output   is  line buffered (see
 262%   set_stream/2).
 263%
 264%   @compat Older versions of this predicate only created this file
 265%           if there was output.
 266%   @see    library(syslog) allows for sending output to the Unix
 267%           logging service.
 268
 269detach_IO :-
 270    current_prolog_flag(pid, Pid),
 271    atom_concat('/tmp/pl-out.', Pid, TmpFile),
 272    open(TmpFile, write, Out, [alias(daemon_output)]),
 273    set_stream(Out, buffer(line)),
 274    detach_IO(Out).
 275
 276:- if(current_predicate(prctl/1)).
 277:- export(prctl/1).
 278
 279%!  prctl(+Option) is det.
 280%
 281%   Access to Linux process control operations.  Defines values for
 282%   Option are:
 283%
 284%     - set_dumpable(+Boolean)
 285%     Control whether the process is allowed to dump core. This
 286%     right is dropped under several uid and gid conditions.
 287%     - get_dumpable(-Boolean)
 288%     Get the value of the dumpable flag.
 289
 290:- endif.
 291
 292:- if(current_predicate(sysconf/1)).
 293:- export(sysconf/1).
 294
 295%!  sysconf(+Conf) is semidet.
 296%
 297%   Access system configuration. See sysconf(1) for details. Conf is
 298%   a term Config(Value), where Value is   always an integer. Config
 299%   is the sysconf() name after removing   =_SC_=  and conversion to
 300%   lowercase. Currently support the   following configuration info:
 301%   =arg_max=,  =child_max=,  =clk_tck=,    =open_max=,  =pagesize=,
 302%   =phys_pages=,     =avphys_pages=,     =nprocessors_conf=     and
 303%   =nprocessors_onln=. Note that not all values may be supported on
 304%   all operating systems.
 305
 306:- endif.
 307
 308                 /*******************************
 309                 *           MESSAGES           *
 310                 *******************************/
 311
 312:- multifile
 313    prolog:message//1.
 314
 315prolog:message(fork(join(T, Status))) -->
 316    [ 'Fork: joining thead ~p (status: ~p)'-[T, Status] ].