1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: jan@swi-prolog.org 5 WWW: https://www.swi-prolog.org 6 Copyright (c) 2008-2026, University of Amsterdam 7 VU University Amsterdam 8 CWI, Amsterdam 9 SWI-Prolog Solutions b.v. 10 All rights reserved. 11 12 Redistribution and use in source and binary forms, with or without 13 modification, are permitted provided that the following conditions 14 are met: 15 16 1. Redistributions of source code must retain the above copyright 17 notice, this list of conditions and the following disclaimer. 18 19 2. Redistributions in binary form must reproduce the above copyright 20 notice, this list of conditions and the following disclaimer in 21 the documentation and/or other materials provided with the 22 distribution. 23 24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 25 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 26 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 28 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 29 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 30 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 32 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 34 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35 POSSIBILITY OF SUCH DAMAGE. 36*/ 37 38:- module(process, 39 [ process_create/3, % +Exe, +Args, +Options 40 process_wait/2, % +PID, -Status 41 process_wait/3, % +PID, -Status, +Options 42 process_id/1, % -PID 43 process_id/2, % +Process, -PID 44 is_process/1, % +PID 45 process_release/1, % +PID 46 process_kill/1, % +PID 47 process_group_kill/1, % +PID 48 process_group_kill/2, % +PID, +Signal 49 process_kill/2, % +PID, +Signal 50 process_which/2, % +Exe, -AbsoluteFile 51 52 process_set_method/1 % +CreateMethod 53 ]). 54:- multifile prolog:prolog_tool/4. 55:- dynamic prolog:prolog_tool/4. 56 57:- autoload(library(apply),[maplist/3]). 58:- autoload(library(error),[must_be/2,existence_error/2]). 59:- autoload(library(option),[select_option/3]). 60 61:- use_foreign_library(foreign(process)). 62 63:- predicate_options(process_create/3, 3, 64 [ stdin(any), 65 stdout(any), 66 stderr(any), 67 cwd(atom), 68 env(list(any)), 69 environment(list(any)), 70 priority(+integer), 71 process(-integer), 72 detached(+boolean), 73 window(+boolean) 74 ]). 75 76/** <module> Create processes and redirect I/O 77 78The module library(process) implements interaction with child processes 79and unifies older interfaces such as shell/[1,2], open(pipe(command), 80...) etc. This library is modelled after SICStus 4. 81 82The main interface is formed by process_create/3. If the process id is 83requested the process must be waited for using process_wait/2. Otherwise 84the process resources are reclaimed automatically. 85 86In addition to the predicates, this module defines a file search path 87(see user:file_search_path/2 and absolute_file_name/3) named `path` that 88locates files on the system's search path for executables. E.g. the 89following finds the executable for `ls`: 90 91 ?- absolute_file_name(path(ls), Path, [access(execute)]). 92 93__Incompatibilities and current limitations__ 94 95 - Where SICStus distinguishes between an internal process id and 96 the OS process id, this implementation does not make this 97 distinction. This implies that is_process/1 is incomplete and 98 unreliable. 99 100 - An extra option env([Name=Value, ...]) is added to 101 process_create/3. As of version 4.1 SICStus added 102 environment(List) which _modifies_ the environment. A 103 compatible option was added to SWI-Prolog 7.7.23. 104 105 - Using prolog(Tool) for `Exe` is a SWI-Prolog extension. 106 107@compat SICStus 4 108*/ 109 110 111%! process_create(+Exe, +Args:list, +Options) is det. 112% 113% Create a new process running the file Exe and using arguments from 114% the given list. Exe is a file specification as handed to 115% absolute_file_name/3. Typically one use the `path` file alias to 116% specify an executable file on the current PATH. The path `prolog` is 117% reserved. If Exe is prolog(Tool), a Prolog utility is invoked that 118% belongs to the distribution of the calling Prolog process. `Tool` is 119% one of ``self``, ``swipl``, ``swipl-win`` or ``swipl-ld``. See 120% prolog:prolog_tool/4 for details. 121% 122% Args is a list of arguments that are handed to the new process. On 123% Unix systems, each element in the list becomes a separate argument 124% in the new process. In Windows, the arguments are simply 125% concatenated to form the commandline. Each argument itself is either 126% a primitive or a list of primitives. A primitive is either atomic or 127% a term file(Spec). Using file(Spec), the system inserts a filename 128% using the OS filename conventions which is properly quoted if 129% needed. 130% 131% Options: 132% 133% - stdin(Spec) 134% - stdout(Spec) 135% - stderr(Spec) 136% Bind the standard streams of the new process. Spec is one of 137% the terms below. If pipe(Pipe) is used, the Prolog stream is a 138% stream in text-mode using the encoding of the default locale. 139% The encoding can be changed using set_stream/2, or by using 140% the two-argument form of `pipe`, which accepts an 141% encoding(Encoding) option. The options `stdout` and `stderr` 142% may use the same stream, in which case both output streams are 143% connected to the same Prolog stream. 144% 145% - std 146% Just share with the Prolog I/O streams. On Unix, if the 147% `user_input`, etc. are bound to a file handle but not to 148% 0,1,2 the process I/O is bound to the file handles of 149% these streams. 150% - null 151% Bind to a _null_ stream. Reading from such a stream 152% returns end-of-file, writing produces no output 153% - pipe(-Stream) 154% - pipe(-Stream, +StreamOptions) 155% Attach input and/or output to a Prolog stream. The 156% optional StreamOptions argument is a list of options that 157% affect the stream. Currently only the options type(+Type) 158% and encoding(+Encoding) are supported, which have the same 159% meaning as the stream properties of the same name (see 160% stream_property/2). StreamOptions is provided mainly for 161% SICStus compatibility - the SWI-Prolog predicate 162% set_stream/2 can be used for the same purpose. 163% - stream(+Stream) 164% Attach input or output to an existing Prolog stream. This 165% stream must be associated with an OS file handle (see 166% stream_property/2, property `file_no`). This option is 167% __not__ provided by the SICStus implementation. 168% 169% - cwd(+Directory) 170% Run the new process in Directory. Directory can be a compound 171% specification, which is converted using absolute_file_name/3. 172% See also process_set_method/1. 173% - env(+List) 174% As environment(List), but _only_ the specified variables 175% are passed, i.e., no variables are _inherited_. 176% - environment(+List) 177% Specify _additional_ environment variables for the new 178% process. List is a list of `Name=Value` terms, where `Value` 179% is expanded the same way as the Args argument. If neither 180% `env` nor `environment` is passed the environment is inherited 181% from the Prolog process. At most one env(List) or 182% environment(List) term may appear in the options. If multiple 183% appear a `permission_error` is raised for the second option. 184% - process(-PID) 185% Unify PID with the process id of the created process. 186% - detached(+Bool) 187% In Unix: If `true`, detach the process from the terminal 188% Currently mapped to setsid(); Also creates a new process group 189% for the child In Windows: If `true`, detach the process from 190% the current job via the CREATE_BREAKAWAY_FROM_JOB flag. In 191% Vista and beyond, processes launched from the shell directly 192% have the 'compatibility assistant' attached to them 193% automatically unless they have a UAC manifest embedded in 194% them. This means that you will get a permission denied error 195% if you try and assign the newly-created PID to a job you 196% create yourself. 197% 198% If neither process(PID) nor any pipe is used the process 199% is moreover _not waited for_: process_create/3 returns 200% as soon as the process is started and its exit status is 201% not available. On POSIX systems this is realised using 202% a second fork(), such that the process is inherited by 203% `init` rather than by us. 204% - window(+Bool) 205% If `true`, create a window for the process (Windows only) 206% - priority(+Priority) 207% In Unix: specifies the process priority for the newly created 208% process. Priority must be an integer between -20 and 19. 209% Positive values are nicer to others, and negative values are 210% less so. The default is zero. Users are free to lower their 211% own priority. Only the super-user may _raise_ it to less-than 212% zero. 213% 214% If the user specifies the process(-PID) option, he __must__ call 215% process_wait/2 to reclaim the process. Without this option, the 216% system will wait for completion of the process after the last pipe 217% stream is closed, unless detached(true) is used. 218% 219% If the process is not waited for, it must succeed with status 0. If 220% not, an process_error is raised. 221% 222% __Windows notes__ 223% 224% On Windows this call is an interface to the CreateProcess() API. The 225% commandline consists of the basename of Exe and the arguments formed 226% from Args. Arguments are separated by a single space. If all 227% characters satisfy iswalnum() it is unquoted. If the argument 228% contains a double-quote it is quoted using single quotes. If both 229% single and double quotes appear a domain_error is raised, otherwise 230% double-quote are used. 231% 232% The CreateProcess() API has many options. Currently only the 233% ``CREATE_NO_WINDOW`` options is supported through the window(+Bool) 234% option. If omitted, the default is to use this option if the 235% application has no console. Future versions are likely to support 236% more window specific options and replace win_exec/2. 237% 238% __Examples__ 239% 240% First, a very simple example that behaves the same as ``shell('ls 241% -l')``, except for error handling: 242% 243% ``` 244% ?- process_create(path(ls), ['-l'], []). 245% ``` 246% 247% The following example uses grep to find all matching lines in a 248% file. 249% 250% ``` 251% grep(File, Pattern, Lines) :- 252% setup_call_cleanup( 253% process_create(path(grep), [ Pattern, file(File) ], 254% [ stdout(pipe(Out)) 255% ]), 256% read_lines(Out, Lines), 257% close(Out)). 258% 259% read_lines(Out, Lines) :- 260% read_line_to_codes(Out, Line1), 261% read_lines(Line1, Out, Lines). 262% 263% read_lines(end_of_file, _, []) :- !. 264% read_lines(Codes, Out, [Line|Lines]) :- 265% atom_codes(Line, Codes), 266% read_line_to_codes(Out, Line2), 267% read_lines(Line2, Out, Lines). 268% ``` 269% 270% @error process_error(Exe, Status) where Status is one of 271% exit(Code) or killed(Signal). Raised if the process 272% is waited for (i.e., Options does not include 273% process(-PID)), and does not exit with status 0. 274% @bug On Windows, environment(List) is handled as env(List), 275% i.e., the environment is not inherited. 276 277process_create(prolog(Prolog), Args, Options) => 278 prolog_executable(Prolog, Exe, Args, Args1), 279 process_create(Exe, Args1, Options). 280process_create(Exe, Args, Options) => 281 ( exe_options(ExeOptions), 282 absolute_file_name(Exe, PlProg, ExeOptions) 283 -> true 284 ), 285 must_be(list, Args), 286 maplist(map_arg, Args, Av), 287 prolog_to_os_filename(PlProg, Prog), 288 Term =.. [Prog|Av], 289 expand_cwd_option(Options, Options1), 290 expand_env_option(env, Options1, Options2), 291 expand_env_option(environment, Options2, Options3), 292 process_create(Term, Options3). 293 294%! prolog_executable(+Tool, -Exe, +ArgvIn, -Argv) is det. 295%! prolog:prolog_tool(+Tool, -Exe, +ArgvIn, -Argv) is semidet. 296% 297% Find the executable and commandline arguments for running Tool. This 298% provides a hook for process_create/3 called as 299% process_create(prolog(Tool), ...). Tool is currently one of: 300% 301% - `self` 302% Run Prolog itself. 303% - `swipl` 304% Run the commandline version, also when called from the 305% ``swipl-win`` _app_. 306% - `swipl-win` 307% Run the ``swipl-win`` _app_, also when called from the 308% commandline version. 309% - `swipl-ld` 310% Run the C/C++ compiler frontend to embed Prolog or build 311% foreign extensions. 312% 313% prolog:prolog_tool/4 is defined as multifile and dynamic and can be 314% used for special cases. This hook is notably intended to provide a 315% portable way of calling Prolog when Prolog is embedded. 316% 317% For example, when using 318% [rswipl](https://cran.r-project.org/web/packages/rolog/vignettes/rswipl.html), 319% we can run Prolog using 320% 321% R -s -e 'rswipl::swipl()' --args <Prolog Argv> 322% 323% We can make process_create(prolog(swipl), ...) work using 324% 325% ``` 326% :- multifile prolog:prolog_tool/4. 327% prolog:prolog_tool(swipl, path('R'), Argv, 328% [ '-s', '-e', 'rswipl::swipl()', '--args' 329% | Argv 330% ]). 331% ``` 332 333prolog_executable(Prolog, Exe, Args0, Args), 334 prolog:prolog_tool(Prolog, Exe, Args0, Args) => 335 true. 336prolog_executable(self, Exe, Args0, Args) => 337 current_prolog_flag(executable, Exe), 338 add_home_option(Args0, Args). 339prolog_executable(Tool, Exe, Args0, Args), 340 swipl_tool(Tool) => 341 current_prolog_flag(executable, Me), 342 neighbour_exe(Tool, Me, Exe), 343 add_home_option(Args0, Args). 344 345swipl_tool(swipl). 346swipl_tool('swipl-win'). 347swipl_tool('swipl-ld'). 348 349neighbour_exe(Target, Me, Exe) :- 350 file_directory_name(Me, Dir), 351 file_name_extension(_, Ext, Me), 352 atomic_list_concat([Dir, Target], '/', Base), 353 file_name_extension(Base, Ext, Exe). 354 355add_home_option(Args0, [HomeOption|Args0]) :- 356 current_prolog_flag(home, Home), 357 format(atom(HomeOption), '--home=~w', [Home]). 358 359%! process_which(+Exe, -Path) is semidet. 360% 361% True when Path is an absolute file name for the specification Exe. 362% This deals with the search path as well as extensions used by the 363% OS. 364 365process_which(Exe, Path) :- 366 exe_options(ExeOptions), 367 absolute_file_name(Exe, Path, [file_errors(fail)|ExeOptions]), 368 !. 369 370%! exe_options(-Options) is multi. 371% 372% Get options for absolute_file_name to find an executable file. On 373% Windows we first look for a readable file, but if this does not 374% exist we are happy with a existing file because the file may be a 375% [reparse point](https://docs.microsoft.com/en-us/windows/win32/fileio/reparse-points-and-file-operations) 376 377exe_options(Options) :- 378 current_prolog_flag(windows, true), 379 !, 380 ( Options = [ extensions(['',exe,com]), access(read), file_errors(fail) ] 381 ; Options = [ extensions(['',exe,com]), access(exist) ] 382 ). 383exe_options(Options) :- 384 Options = [ access(execute) ]. 385 386expand_cwd_option(Options0, Options) :- 387 select_option(cwd(Spec), Options0, Options1), 388 !, 389 ( compound(Spec) 390 -> absolute_file_name(Spec, PlDir, [file_type(directory), access(read)]), 391 prolog_to_os_filename(PlDir, Dir), 392 Options = [cwd(Dir)|Options1] 393 ; exists_directory(Spec) 394 -> Options = Options0 395 ; existence_error(directory, Spec) 396 ). 397expand_cwd_option(Options, Options). 398 399expand_env_option(Name, Options0, Options) :- 400 Term =.. [Name,Value0], 401 select_option(Term, Options0, Options1), 402 !, 403 must_be(list, Value0), 404 maplist(map_env, Value0, Value), 405 NewOption =.. [Name,Value], 406 Options = [NewOption|Options1]. 407expand_env_option(_, Options, Options). 408 409map_env(Name=Value0, Name=Value) :- 410 map_arg(Value0, Value). 411 412%! map_arg(+ArgIn, -Arg) is det. 413% 414% Map an individual argument. Primitives are either file(Spec) or 415% an atomic value (atom, string, number). If ArgIn is a non-empty 416% list, all elements are converted and the results are 417% concatenated. 418 419map_arg([], []) :- !. 420map_arg(List, Arg) :- 421 is_list(List), 422 !, 423 maplist(map_arg_prim, List, Prims), 424 atomic_list_concat(Prims, Arg). 425map_arg(Prim, Arg) :- 426 map_arg_prim(Prim, Arg). 427 428map_arg_prim(file(Spec), File) :- 429 !, 430 ( compound(Spec) 431 -> absolute_file_name(Spec, PlFile) 432 ; PlFile = Spec 433 ), 434 prolog_to_os_filename(PlFile, File). 435map_arg_prim(Arg, Arg). 436 437 438%! process_id(-PID) is det. 439% 440% True if PID is the process id of the running Prolog process. 441% 442% @deprecated Use current_prolog_flag(pid, PID) 443 444process_id(PID) :- 445 current_prolog_flag(pid, PID). 446 447%! process_id(+Process, -PID) is det. 448% 449% PID is the process id of Process. Given that they are united in 450% SWI-Prolog, this is a simple unify. 451 452process_id(PID, PID). 453 454%! is_process(+PID) is semidet. 455% 456% True if PID might be a process. Succeeds for any positive 457% integer. 458 459is_process(PID) :- 460 integer(PID), 461 PID > 0. 462 463%! process_release(+PID) 464% 465% Release process handle. In this implementation this is the same 466% as process_wait(PID, _). 467 468process_release(PID) :- 469 process_wait(PID, _). 470 471%! process_wait(+PID, -Status) is det. 472%! process_wait(+PID, -Status, +Options) is det. 473% 474% True if PID completed with Status. This call normally blocks 475% until the process is finished. Options: 476% 477% * timeout(+Timeout) 478% Default: `infinite`. If this option is a number, the 479% waits for a maximum of Timeout seconds and unifies Status 480% with `timeout` if the process does not terminate within 481% Timeout. In this case PID is _not_ invalidated. On Unix 482% systems only timeout 0 and `infinite` are supported. A 483% 0-value can be used to poll the status of the process. 484% 485% * release(+Bool) 486% Do/do not release the process. We do not support this flag 487% and a domain_error is raised if release(false) is provided. 488% 489% @arg Status is one of exit(Code) or killed(Signal), where 490% Code and Signal are integers. If the `timeout` option 491% is used Status is unified with `timeout` after the wait 492% timed out. 493 494process_wait(PID, Status) :- 495 process_wait(PID, Status, []). 496 497%! process_kill(+PID) is det. 498%! process_kill(+PID, +Signal) is det. 499% 500% Send signal to process PID. Default is `term`. Signal is an 501% integer, Unix signal name (e.g. `SIGSTOP`) or the more Prolog 502% friendly variation one gets after removing `SIG` and downcase 503% the result: `stop`. On Windows systems, Signal is ignored and 504% the process is terminated using the TerminateProcess() API. On 505% Windows systems PID must be obtained from process_create/3, 506% while any PID is allowed on Unix systems. 507% 508% @compat SICStus does not accept the prolog friendly version. We 509% choose to do so for compatibility with on_signal/3. 510 511process_kill(PID) :- 512 process_kill(PID, term). 513 514 515%! process_group_kill(+PID) is det. 516%! process_group_kill(+PID, +Signal) is det. 517% 518% Send signal to the group containing process PID. Default is 519% `term`. See process_wait/1 for a description of signal 520% handling. In Windows, the same restriction on PID applies: it 521% must have been created from process_create/3, and the the group 522% is terminated via the TerminateJobObject API. 523 524process_group_kill(PID) :- 525 process_group_kill(PID, term). 526 527 528%! process_set_method(+Method) is det. 529% 530% Determine how the process is created on Unix systems. Method is one 531% of `spawn` (default), `fork` or `vfork`. If the method is `spawn` 532% but this cannot be used because it is either not supported by the OS 533% or the cwd(Dir) option is given `fork` is used. 534% 535% The problem is to be understood as follows. The official portable 536% and safe method to create a process is using the fork() system call. 537% This call however copies the process page tables and get seriously 538% slow as the (Prolog) process is multiple giga bytes large. 539% Alternatively, we may use vfork() which avoids copying the process 540% space. But, the safe usage as guaranteed by the POSIX standard of 541% vfork() is insufficient for our purposes. On practical systems your 542% mileage may vary. Modern posix systems also provide posix_spawn(), 543% which provides a safe and portable alternative for the fork() and 544% exec() sequence that may be implemented using fork() or may use a 545% fast but safe alternative. Unfortunately posix_spawn() doesn't 546% support the option to specify the working directory for the child 547% and we cannot use working_directory/2 as the working directory is 548% shared between threads. 549% 550% Summarizing, the default is safe and tries to be as fast as 551% possible. On some scenarios and on some OSes it is possible to do 552% better. It is generally a good idea to avoid using the cwd(Dir) 553% option of process_create/3 as without we can use posix_spawn(). 554 555 556 /******************************* 557 * MESSAGES * 558 *******************************/ 559 560:- multifile 561 prolog:error_message/3. 562 563prologerror_message(process_error(File, exit(Status))) --> 564 [ 'Process "~w": exit status: ~w'-[File, Status] ]. 565prologerror_message(process_error(File, killed(Signal))) --> 566 [ 'Process "~w": killed by signal ~w'-[File, Signal] ]. 567prologerror_message(existence_error(source_sink, path(Exe))) --> 568 [ 'Could not find executable file "~p" in '-[Exe] ], 569 path_var. 570 571path_var --> 572 ( { current_prolog_flag(windows, true) } 573 -> [ '%PATH%'-[] ] 574 ; [ '$PATH'-[] ] 575 )