% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\section{library(unix): Unix specific operations}

\label{sec:unix}

\begin{tags}
    \tag{See also}
\verb$library(process)$ provides a portable high level interface to create
and manage processes.
\end{tags}

The \verb$library(unix)$ library provides the commonly used Unix primitives to
deal with process management. These primitives are useful for many
tasks, including server management, parallel computation, exploiting and
controlling other processes, etc.

The predicates in this library are modelled closely after their native
Unix counterparts.\vspace{0.7cm}

\begin{description}
    \predicate[det]{fork}{1}{-Pid}
Clone the current process into two branches. In the child, \arg{Pid}
is unified to child. In the original process, \arg{Pid} is unified to
the process identifier of the created child. Both parent and
child are fully functional Prolog processes running the same
program. The processes share open I/O streams that refer to Unix
native streams, such as files, sockets and pipes. Data is not
shared, though on most Unix systems data is initially shared and
duplicated only if one of the programs attempts to modify the
data.

Unix \verb$fork()$ is the only way to create new processes and \predref{fork}{1}
is a simple direct interface to it.

\begin{tags}
    \tag{Errors}
\verb$permission_error(fork, process, main)$ is raised if
the calling thread is not the only thread in the
process. Forking a Prolog process with threads
will typically deadlock because only the calling
thread is cloned in the fork, while all thread
synchronization are cloned.
\end{tags}

    \predicate[det]{fork_exec}{1}{+Command}
Fork (as \predref{fork}{1}) and exec (using \predref{exec}{1}) the child immediately.
This behaves as the code below, but bypasses the check for the
existence of other threads because this is a safe scenario.

\begin{code}
fork_exec(Command) :-
      (   fork(child)
      ->  exec(Command)
      ;   true
      ).
\end{code}

    \predicate{exec}{1}{+Command}
Replace the running program by starting \arg{Command}. \arg{Command} is a
callable term. The functor is the command and the arguments
provide the command-line arguments for the command. Each
command-line argument must be atomic and is converted to a
string before passed to the Unix call \verb$execvp()$. Here are some
examples:

\begin{shortlist}
    \item \verb$exec(ls('-l'))$
    \item \verb$exec('/bin/ls'('-l', '/home/jan'))$
\end{shortlist}

Unix \verb$exec()$ is the only way to start an executable file
executing. It is commonly used together with \predref{fork}{1}. For example
to start netscape on an URL in the background, do:

\begin{code}
run_netscape(URL) :-
        (    fork(child),
             exec(netscape(URL))
        ;    true
        ).
\end{code}

Using this code, netscape remains part of the process-group of
the invoking Prolog process and Prolog does not wait for
netscape to terminate. The predicate \predref{wait}{2} allows waiting for a
child, while \predref{detach_IO}{0} disconnects the child as a deamon
process.

    \predicate[det]{wait}{2}{?Pid, -Status}
Wait for a child to change status. Then report the child that
changed status as well as the reason. If \arg{Pid} is bound on entry
then the status of the specified child is reported. If not, then
the status of any child is reported. \arg{Status} is unified with
\verb$exited(ExitCode)$ if the child with pid \arg{Pid} was terminated by
calling \verb$exit()$ (Prolog \predref{halt}{1}). ExitCode is the return status.
\arg{Status} is unified with \verb$signaled(Signal)$ if the child died due to
a software interrupt (see \predref{kill}{2}). Signal contains the signal
number. Finally, if the process suspended execution due to a
signal, \arg{Status} is unified with \verb$stopped(Signal)$.

    \predicate[det]{kill}{2}{+Pid, +Signal}
Deliver a software interrupt to the process with identifier \arg{Pid}
using software-interrupt number \arg{Signal}. See also \predref{on_signal}{2}.
Signals can be specified as an integer or signal name, where
signal names are derived from the C constant by dropping the
\verb$SIG$ prefix and mapping to lowercase. E.g. \const{int} is the same as
\verb$SIGINT$ in C. The meaning of the signal numbers can be found in
the Unix manual.

    \predicate[det]{pipe}{2}{-InSream, -OutStream}
Create a communication-pipe. This is normally used to make a
child communicate to its parent. After \predref{pipe}{2}, the process is
cloned and, depending on the desired direction, both processes
close the end of the pipe they do not use. Then they use the
remaining stream to communicate. Here is a simple example:

\begin{code}
:- use_module(library(unix)).

fork_demo(Result) :-
        pipe(Read, Write),
        fork(Pid),
        (   Pid == child
        ->  close(Read),
            format(Write, '~q.~n',
                   [hello(world)]),
            flush_output(Write),
            halt
        ;   close(Write),
            read(Read, Result),
            close(Read)
        ).
\end{code}

    \predicate[det]{dup}{2}{+FromStream, +ToStream}
Interface to Unix \verb$dup2()$, copying the underlying filedescriptor
and thus making both streams point to the same underlying
object. This is normally used together with \predref{fork}{1} and \predref{pipe}{2} to
talk to an external program that is designed to communicate
using standard I/O.

Both \arg{FromStream} and \arg{ToStream} either refer to a Prolog stream or
an integer descriptor number to refer directly to OS
descriptors. See also \file{demo/pipe.pl} in the source-distribution of
this package.

    \predicate[det]{detach_IO}{1}{+Stream}
This predicate is intended to create Unix \textit{deamon} processes. It
performs two actions.

\begin{enumerate}
    \item The I/O streams \verb$user_input$, \verb$user_output$ and
\verb$user_error$ are closed if they are connected to a terminal
(see \const{tty} property in \predref{stream_property}{2}). Input streams are
rebound to a dummy stream that returns EOF. Output streams are
reboud to forward their output to \arg{Stream}.
    \item The process is detached from the current process-group and
its controlling terminal. This is achieved using \verb$setsid()$ if
provided or using \verb$ioctl()$ \verb$TIOCNOTTY$ on \verb$/dev/tty$.
\end{enumerate}

To ignore all output, it may be rebound to a null stream. For
example:

\begin{code}
      ...,
      open_null_stream(Out),
      detach_IO(Out).
\end{code}

The \predref{detach_IO}{1} should be called only once per process.
Subsequent calls silently succeed without any side effects.

\begin{tags}
    \tag{See also}
\predref{detach_IO}{0} and \verb$library(syslog)$.
\end{tags}

    \predicate[det]{detach_IO}{0}{}
Detach I/O similar to \predref{detach_IO}{1}. The output streams are bound
to a file \verb$/tmp/pl-out.<pid>$. Output is line buffered (see
\predref{set_stream}{2}).

\begin{tags}
    \tag{See also}
\verb$library(syslog)$ allows for sending output to the Unix
logging service.
    \tag{Compatibility}
Older versions of this predicate only created this file
if there was output.
\end{tags}

    \predicate[semidet]{sysconf}{1}{+Conf}
Access system configuration. See \verb$sysconf(1)$ for details. \arg{Conf} is
a term Config(Value), where Value is always an integer. Config
is the \verb$sysconf()$ name after removing =_SC_= and conversion to
lowercase. Currently support the following configuration info:
\verb$arg_max$, \verb$child_max$, \verb$clk_tck$, \verb$open_max$, \const{pagesize},
\verb$phys_pages$, \verb$avphys_pages$, \verb$nprocessors_conf$ and
\verb$nprocessors_onln$. Note that not all values may be supported on
all operating systems.
\end{description}

