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