Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ......

22
Package ‘processx’ November 30, 2020 Title Execute and Control System Processes Version 3.4.5 Description Tools to run system processes in the background. It can check if a background process is running; wait on a background process to finish; get the exit status of finished processes; kill background processes. It can read the standard output and error of the processes, using non-blocking connections. 'processx' can poll a process for standard output or error, with a timeout. It can also poll several processes at once. License MIT + file LICENSE LazyData true URL https://processx.r-lib.org, https://github.com/r-lib/processx#readme BugReports https://github.com/r-lib/processx/issues RoxygenNote 7.1.1 Imports ps (>= 1.2.0), R6, utils Suggests callr (>= 3.2.0), codetools, covr, crayon, curl, debugme, parallel, testthat, withr Encoding UTF-8 NeedsCompilation yes Author Gábor Csárdi [aut, cre, cph] (<https://orcid.org/0000-0001-7098-9676>), Winston Chang [aut], RStudio [cph, fnd], Mango Solutions [cph, fnd] Maintainer Gábor Csárdi <[email protected]> Repository CRAN Date/Publication 2020-11-30 11:40:02 UTC 1

Transcript of Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ......

Page 1: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

Package ‘processx’November 30, 2020

Title Execute and Control System Processes

Version 3.4.5

Description Tools to run system processes in the background.It can check if a background process is running; wait on a backgroundprocess to finish; get the exit status of finished processes; killbackground processes. It can read the standard output and error ofthe processes, using non-blocking connections. 'processx' can polla process for standard output or error, with a timeout. It can alsopoll several processes at once.

License MIT + file LICENSE

LazyData true

URL https://processx.r-lib.org,

https://github.com/r-lib/processx#readme

BugReports https://github.com/r-lib/processx/issues

RoxygenNote 7.1.1

Imports ps (>= 1.2.0), R6, utils

Suggests callr (>= 3.2.0), codetools, covr, crayon, curl, debugme,parallel, testthat, withr

Encoding UTF-8

NeedsCompilation yes

Author Gábor Csárdi [aut, cre, cph] (<https://orcid.org/0000-0001-7098-9676>),Winston Chang [aut],RStudio [cph, fnd],Mango Solutions [cph, fnd]

Maintainer Gábor Csárdi <[email protected]>

Repository CRAN

Date/Publication 2020-11-30 11:40:02 UTC

1

Page 2: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

2 conn_create_fd

R topics documented:

base64_decode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2conn_create_fd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2curl_fds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5default_pty_options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5poll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Index 22

base64_decode Base64 Encoding and Decoding

Description

Base64 Encoding and Decoding

Usage

base64_decode(x)

base64_encode(x)

Arguments

x Raw vector to encode / decode.

Value

Raw vector, result of the encoding / decoding.

conn_create_fd Processx connections

Description

These functions are currently experimental and will change in the future. Note that processx con-nections are not compatible with R’s built-in connection system.

Page 3: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

conn_create_fd 3

Usage

conn_create_fd(fd, encoding = "", close = TRUE)

conn_create_pipepair(encoding = "", nonblocking = c(TRUE, FALSE))

conn_read_chars(con, n = -1)

## S3 method for class 'processx_connection'conn_read_chars(con, n = -1)

processx_conn_read_chars(con, n = -1)

conn_read_lines(con, n = -1)

## S3 method for class 'processx_connection'conn_read_lines(con, n = -1)

processx_conn_read_lines(con, n = -1)

conn_is_incomplete(con)

## S3 method for class 'processx_connection'conn_is_incomplete(con)

processx_conn_is_incomplete(con)

conn_write(con, str, sep = "\n", encoding = "")

## S3 method for class 'processx_connection'conn_write(con, str, sep = "\n", encoding = "")

processx_conn_write(con, str, sep = "\n", encoding = "")

conn_create_file(filename, read = NULL, write = NULL)

conn_set_stdout(con, drop = TRUE)

conn_set_stderr(con, drop = TRUE)

conn_get_fileno(con)

conn_disable_inheritance()

## S3 method for class 'processx_connection'close(con, ...)

processx_conn_close(con, ...)

Page 4: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

4 conn_create_fd

Arguments

fd Integer scalar, a Unix file descriptor.

encoding Encoding of the readable connection when reading.

close Whether to close the OS file descriptor when closing the connection. Sometimesyou want to leave it open, and use it again in a conn_create_fd call. Encodingto re-encode str into when writing.

nonblocking Whether the writeable and the readable ends of the pipe should be non-blockingconnections.

con Processx connection object.

n Number of characters or lines to read. -1 means all available characters or lines.

str Character or raw vector to write.

sep Separator to use if str is a character vector. Ignored if str is a raw vector.

filename File name.

read Whether the connection is readable.

write Whethe the connection is writeable.

drop Whether to close the original stdout/stderr, or keep it open and return a connec-tion to it.

... Extra arguments, for compatibility with the close() generic, currently ignoredby processx.

Details

conn_create_fd() creates a connection from a file descriptor.

conn_create_pipepair() creates a pair of connected connections, the first one is writeable, thesecond one is readable.

conn_read_chars() reads UTF-8 characters from the connections. If the connection itself is notUTF-8 encoded, it re-encodes it.

conn_read_lines() reads lines from a connection.

conn_is_incomplete() returns FALSE if the connection surely has no more data.

conn_write() writes a character or raw vector to the connection. It might not be able to writeall bytes into the connection, in which case it returns the leftover bytes in a raw vector. Callconn_write() again with this raw vector.

conn_create_file() creates a connection to a file.

conn_set_stdout() set the standard output of the R process, to the specified connection.

conn_set_stderr() set the standard error of the R process, to the specified connection.

conn_get_fileno() return the integer file desciptor that belongs to the connection.

conn_disable_inheritance() can be called to disable the inheritance of all open handles. Callthis function as soon as possible in a new process to avoid inheriting the inherited handles evenfurther. The function is best effort to close the handles, it might still leave some handles open. Itshould work for stdin, stdout and stderr, at least.

Page 5: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

curl_fds 5

curl_fds Create a pollable object from a curl multi handle’s file descriptors

Description

Create a pollable object from a curl multi handle’s file descriptors

Usage

curl_fds(fds)

Arguments

fds A list of file descriptors, as returned by curl::multi_fdset().

Value

Pollable object, that be used with poll() directly.

default_pty_options Default options for pseudo terminals (ptys)

Description

Default options for pseudo terminals (ptys)

Usage

default_pty_options()

Value

Named list of default values of pty options.

Options and default values:

• echo whether to keep the echo on the terminal. FALSE turns echo off.

• rows the (initial) terminal size, number of rows.

• cols the (initial) terminal size, number of columns.

Page 6: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

6 poll

poll Poll for process I/O or termination

Description

Wait until one of the specified connections or processes produce standard output or error, terminates,or a timeout occurs.

Usage

poll(processes, ms)

Arguments

processes A list of connection objects orprocess objects to wait on. (They can be mixedas well.) If this is a named list, then the returned list will have the same names.This simplifies the identification of the processes.

ms Integer scalar, a timeout for the polling, in milliseconds. Supply -1 for an infititetimeout, and 0 for not waiting at all.

Value

A list of character vectors of length one or three. There is one list element for each connec-tion/process, in the same order as in the input list. For connections the result is a single stringscalar. For processes the character vectors’ elements are named output, error and process. Pos-sible values for each individual result are: nopipe, ready, timeout, closed, silent. See detailsabout these below. process refers to the poll connection, see the poll_connection argument ofthe process initializer.

Explanation of the return values

• nopipe means that the stdout or stderr from this process was not captured.

• ready means that the connection or the stdout or stderr from this process are ready to readfrom. Note that end-of-file on these outputs also triggers ready.

• timeout‘: the connections or processes are not ready to read from and a timeout happened.

• closed: the connection was already closed, before the polling started.

• silent: the connection is not ready to read from, but another connection was.

Examples

# Different commands to run for windows and unixcmd1 <- switch(

.Platform$OS.type,"unix" = c("sh", "-c", "sleep 1; ls"),c("cmd", "/c", "ping -n 2 127.0.0.1 && dir /b")

)

Page 7: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 7

cmd2 <- switch(.Platform$OS.type,"unix" = c("sh", "-c", "sleep 2; ls 1>&2"),c("cmd", "/c", "ping -n 2 127.0.0.1 && dir /b 1>&2")

)

## Run them. p1 writes to stdout, p2 to stderr, after some sleepp1 <- process$new(cmd1[1], cmd1[-1], stdout = "|")p2 <- process$new(cmd2[1], cmd2[-1], stderr = "|")

## Nothing to read initiallypoll(list(p1 = p1, p2 = p2), 0)

## Wait until p1 finishes. Now p1 has some outputp1$wait()poll(list(p1 = p1, p2 = p2), -1)

## Close p1's connection, p2 will have output on stderr, eventuallyclose(p1$get_output_connection())poll(list(p1 = p1, p2 = p2), -1)

## Close p2's connection as well, no nothing to pollclose(p2$get_error_connection())poll(list(p1 = p1, p2 = p2), 0)

process External process

Description

Managing external processes from R is not trivial, and this class aims to help with this deficiency.It is essentially a small wrapper around the system base R function, to return the process id of thestarted process, and set its standard output and error streams. The process id is then used to managethe process.

Polling

The poll_io() function polls the standard output and standard error connections of a process, witha timeout. If there is output in either of them, or they are closed (e.g. because the process exits)poll_io() returns immediately.

In addition to polling a single process, the poll() function can poll the output of several processes,and returns as soon as any of them has generated output (or exited).

Cleaning up background processes

processx kills processes that are not referenced any more (if cleanup is set to TRUE), or the wholesubprocess tree (if cleanup_tree is also set to TRUE).

Page 8: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

8 process

The cleanup happens when the references of the processes object are garbage collected. To cleanup earlier, you can call the kill() or kill_tree() method of the process(es), from an on.exit()expression, or an error handler:

process_manager <- function() {on.exit({try(p1$kill(), silent = TRUE)try(p2$kill(), silent = TRUE)

}, add = TRUE)p1 <- process$new("sleep", "3")p2 <- process$new("sleep", "10")p1$wait()p2$wait()

}process_manager()

If you interrupt process_manager() or an error happens then both p1 and p2 are cleaned up im-mediately. Their connections will also be closed. The same happens at a regular exit.

Methods

Public methods:• process$new()

• process$finalize()

• process$kill()

• process$kill_tree()

• process$signal()

• process$interrupt()

• process$get_pid()

• process$is_alive()

• process$wait()

• process$get_exit_status()

• process$format()

• process$print()

• process$get_start_time()

• process$is_supervised()

• process$supervise()

• process$read_output()

• process$read_error()

• process$read_output_lines()

• process$read_error_lines()

• process$is_incomplete_output()

• process$is_incomplete_error()

• process$has_input_connection()

• process$has_output_connection()

Page 9: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 9

• process$has_error_connection()

• process$has_poll_connection()

• process$get_input_connection()

• process$get_output_connection()

• process$get_error_connection()

• process$read_all_output()

• process$read_all_error()

• process$read_all_output_lines()

• process$read_all_error_lines()

• process$write_input()

• process$get_input_file()

• process$get_output_file()

• process$get_error_file()

• process$poll_io()

• process$get_poll_connection()

• process$get_result()

• process$as_ps_handle()

• process$get_name()

• process$get_exe()

• process$get_cmdline()

• process$get_status()

• process$get_username()

• process$get_wd()

• process$get_cpu_times()

• process$get_memory_info()

• process$suspend()

• process$resume()

Method new(): Start a new process in the background, and then return immediately.

Usage:process$new(command = NULL,args = character(),stdin = NULL,stdout = NULL,stderr = NULL,pty = FALSE,pty_options = list(),connections = list(),poll_connection = NULL,env = NULL,cleanup = TRUE,cleanup_tree = FALSE,wd = NULL,

Page 10: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

10 process

echo_cmd = FALSE,supervise = FALSE,windows_verbatim_args = FALSE,windows_hide_window = FALSE,encoding = "",post_process = NULL

)

Arguments:

command Character scalar, the command to run. Note that this argument is not passed to a shell,so no tilde-expansion or variable substitution is performed on it. It should not be quotedwith base::shQuote(). See base::normalizePath() for tilde-expansion.

args Character vector, arguments to the command. They will be passed to the process as is,without a shell transforming them, They don’t need to be escaped.

stdin What to do with the standard input. Possible values:• NULL: set to the null device, i.e. no standard input is provided;• a file name, use this file as standard input;• "|": create a (writeable) connection for stdin.

stdout What to do with the standard output. Possible values:• NULL: discard it;• a string, redirect it to this file;• "|": create a connection for it.

stderr What to do with the standard error. Possible values:• NULL: discard it;• a string, redirect it to this file;• "|": create a connection for it;• "2>&1": redirect it to the same connection (i.e. pipe or file) as stdout. "2>&1" is a way

to keep standard output and error correctly interleaved.pty Whether to create a pseudo terminal (pty) for the background process. This is currently

only supported on Unix systems, but not supported on Solaris. If it is TRUE, then the stdin,stdout and stderr arguments must be NULL. If a pseudo terminal is created, then processxwill create pipes for standard input and standard output. There is no separate pipe for stan-dard error, because there is no way to distinguish between stdout and stderr on a pty. Notethat the standard output connection of the pty is blocking, so we always poll the standardoutput connection before reading from it using the $read_output() method. Also, because$read_output_lines() could still block if no complete line is available, this function alwaysfails if the process has a pty. Use $read_output() to read from ptys.

pty_options Unix pseudo terminal options, a named list. see default_pty_options() fordetails and defaults.

connections A list of processx connections to pass to the child process. This is an experimen-tal feature currently.

poll_connection Whether to create an extra connection to the process that allows polling,even if the standard input and standard output are not pipes. If this is NULL (the default),then this connection will be only created if standard output and standard error are not pipes,and connections is an empty list. If the poll connection is created, you can query it viap$get_poll_connection() and it is also included in the response to p$poll_io() and

Page 11: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 11

poll(). The numeric file descriptor of the poll connection comes right after stderr (2),and the connections listed in connections.

env Environment variables of the child process. If NULL, the parent’s environment is inher-ited. On Windows, many programs cannot function correctly if some environment variablesare not set, so we always set HOMEDRIVE, HOMEPATH, LOGONSERVER, PATH, SYSTEMDRIVE,SYSTEMROOT, TEMP, USERDOMAIN, USERNAME, USERPROFILE and WINDIR.

cleanup Whether to kill the process when the process object is garbage collected.cleanup_tree Whether to kill the process and its child process tree when the process object

is garbage collected.wd Working directory of the process. It must exist. If NULL, then the current working directory

is used.echo_cmd Whether to print the command to the screen before running it.supervise Whether to register the process with a supervisor. If TRUE, the supervisor will ensure

that the process is killed when the R process exits.windows_verbatim_args Whether to omit quoting the arguments on Windows. It is ignored

on other platforms.windows_hide_window Whether to hide the application’s window on Windows. It is ignored

on other platforms.encoding The encoding to assume for stdin, stdout and stderr. By default the encoding of

the current locale is used. Note that processx always reencodes the output of the stdoutand stderr streams in UTF-8 currently. If you want to read them without any conversion,on all platforms, specify "UTF-8" as encoding.

post_process An optional function to run when the process has finished. Currently it onlyruns if $get_result() is called. It is only run once.

Returns: R6 object representing the process.

Method finalize(): Cleanup method that is called when the process object is garbage col-lected. If requested so in the process constructor, then it eliminates all processes in the process’ssubprocess tree.

Usage:process$finalize()

Method kill(): Terminate the process. It also terminate all of its child processes, except ifthey have created a new process group (on Unix), or job object (on Windows). It returns TRUE ifthe process was terminated, and FALSE if it was not (because it was already finished/dead whenprocessx tried to terminate it).

Usage:process$kill(grace = 0.1, close_connections = TRUE)

Arguments:

grace Currently not used.close_connections Whether to close standard input, standard output, standard error connec-

tions and the poll connection, after killing the process.

Method kill_tree(): Process tree cleanup. It terminates the process (if still alive), togetherwith any child (or grandchild, etc.) processes. It uses the ps package, so that needs to be installed,

Page 12: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

12 process

and ps needs to support the current platform as well. Process tree cleanup works by markingthe process with an environment variable, which is inherited in all child processes. This allowsfinding descendents, even if they are orphaned, i.e. they are not connected to the root of the treecleanup in the process tree any more. $kill_tree() returns a named integer vector of the processids that were killed, the names are the names of the processes (e.g. "sleep", "notepad.exe","Rterm.exe", etc.).

Usage:process$kill_tree(grace = 0.1, close_connections = TRUE)

Arguments:grace Currently not used.close_connections Whether to close standard input, standard output, standard error connec-

tions and the poll connection, after killing the process.

Method signal(): Send a signal to the process. On Windows only the SIGINT, SIGTERM andSIGKILL signals are interpreted, and the special 0 signal. The first three all kill the process. The 0signal returns TRUE if the process is alive, and FALSE otherwise. On Unix all signals are supportedthat the OS supports, and the 0 signal as well.

Usage:process$signal(signal)

Arguments:signal An integer scalar, the id of the signal to send to the process. See tools::pskill() for

the list of signals.

Method interrupt(): Send an interrupt to the process. On Unix this is a SIGINT signal,and it is usually equivalent to pressing CTRL+C at the terminal prompt. On Windows, it is aCTRL+BREAK keypress. Applications may catch these events. By default they will quit.

Usage:process$interrupt()

Method get_pid(): Query the process id.

Usage:process$get_pid()

Returns: Integer scalar, the process id of the process.

Method is_alive(): Check if the process is alive.

Usage:process$is_alive()

Returns: Logical scalar.

Method wait(): Wait until the process finishes, or a timeout happens. Note that if the pro-cess never finishes, and the timeout is infinite (the default), then R will never regain control.In some rare cases, $wait() might take a bit longer than specified to time out. This happenson Unix, when another package overwrites the processx SIGCHLD signal handler, after the pro-cessx process has started. One such package is parallel, if used with fork clusters, e.g. throughparallel::mcparallel().

Page 13: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 13

Usage:process$wait(timeout = -1)

Arguments:timeout Timeout in milliseconds, for the wait or the I/O polling.

Returns: It returns the process itself, invisibly.

Method get_exit_status(): $get_exit_status returns the exit code of the process if it has fin-ished and NULL otherwise. On Unix, in some rare cases, the exit status might be NA. This happensif another package (or R itself) overwrites the processx SIGCHLD handler, after the processx pro-cess has started. In these cases processx cannot determine the real exit status of the process. Onesuch package is parallel, if used with fork clusters, e.g. through the parallel::mcparallel()function.

Usage:process$get_exit_status()

Method format(): format(p) or p$format() creates a string representation of the process,usually for printing.

Usage:process$format()

Method print(): print(p) or p$print() shows some information about the process on thescreen, whether it is running and it’s process id, etc.

Usage:process$print()

Method get_start_time(): $get_start_time() returns the time when the process was started.

Usage:process$get_start_time()

Method is_supervised(): $is_supervised() returns whether the process is being tracked bysupervisor process.

Usage:process$is_supervised()

Method supervise(): $supervise() if passed TRUE, tells the supervisor to start tracking theprocess. If FALSE, tells the supervisor to stop tracking the process. Note that even if the supervisoris disabled for a process, if it was started with cleanup = TRUE, the process will still be killed whenthe object is garbage collected.

Usage:process$supervise(status)

Arguments:status Whether to turn on of off the supervisor for this process.

Method read_output(): $read_output() reads from the standard output connection of the pro-cess. If the standard output connection was not requested, then then it returns an error. It uses anon-blocking text connection. This will work only if stdout="|" was used. Otherwise, it willthrow an error.

Page 14: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

14 process

Usage:process$read_output(n = -1)

Arguments:

n Number of characters or lines to read.

Method read_error(): $read_error() is similar to $read_output, but it reads from the standarderror stream.

Usage:process$read_error(n = -1)

Arguments:

n Number of characters or lines to read.

Method read_output_lines(): $read_output_lines() reads lines from standard output connec-tion of the process. If the standard output connection was not requested, then it returns an error.It uses a non-blocking text connection. This will work only if stdout="|" was used. Otherwise,it will throw an error.

Usage:process$read_output_lines(n = -1)

Arguments:

n Number of characters or lines to read.

Method read_error_lines(): $read_error_lines() is similar to $read_output_lines, but it readsfrom the standard error stream.

Usage:process$read_error_lines(n = -1)

Arguments:

n Number of characters or lines to read.

Method is_incomplete_output(): $is_incomplete_output() return FALSE if the other end ofthe standard output connection was closed (most probably because the process exited). It returnTRUE otherwise.

Usage:process$is_incomplete_output()

Method is_incomplete_error(): $is_incomplete_error() return FALSE if the other end of thestandard error connection was closed (most probably because the process exited). It return TRUEotherwise.

Usage:process$is_incomplete_error()

Method has_input_connection(): $has_input_connection() return TRUE if there is a connec-tion object for standard input; in other words, if stdout="|". It returns FALSE otherwise.

Usage:process$has_input_connection()

Page 15: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 15

Method has_output_connection(): $has_output_connection() returns TRUE if there is a con-nection object for standard output; in other words, if stdout="|". It returns FALSE otherwise.

Usage:process$has_output_connection()

Method has_error_connection(): $has_error_connection() returns TRUE if there is a connec-tion object for standard error; in other words, if stderr="|". It returns FALSE otherwise.

Usage:process$has_error_connection()

Method has_poll_connection(): $has_poll_connection() return TRUE if there is a poll con-nection, FALSE otherwise.

Usage:process$has_poll_connection()

Method get_input_connection(): $get_input_connection() returns a connection object, tothe standard input stream of the process.

Usage:process$get_input_connection()

Method get_output_connection(): $get_output_connection() returns a connection object, tothe standard output stream of the process.

Usage:process$get_output_connection()

Method get_error_connection(): $get_error_conneciton() returns a connection object, to thestandard error stream of the process.

Usage:process$get_error_connection()

Method read_all_output(): $read_all_output() waits for all standard output from the process.It does not return until the process has finished. Note that this process involves waiting for theprocess to finish, polling for I/O and potentically several readLines() calls. It returns a characterscalar. This will return content only if stdout="|" was used. Otherwise, it will throw an error.

Usage:process$read_all_output()

Method read_all_error(): $read_all_error() waits for all standard error from the process.It does not return until the process has finished. Note that this process involves waiting for theprocess to finish, polling for I/O and potentically several readLines() calls. It returns a characterscalar. This will return content only if stderr="|" was used. Otherwise, it will throw an error.

Usage:process$read_all_error()

Page 16: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

16 process

Method read_all_output_lines(): $read_all_output_lines() waits for all standard outputlines from a process. It does not return until the process has finished. Note that this processinvolves waiting for the process to finish, polling for I/O and potentically several readLines()calls. It returns a character vector. This will return content only if stdout="|" was used. Other-wise, it will throw an error.

Usage:process$read_all_output_lines()

Method read_all_error_lines(): $read_all_error_lines() waits for all standard error linesfrom a process. It does not return until the process has finished. Note that this process involveswaiting for the process to finish, polling for I/O and potentically several readLines() calls. Itreturns a character vector. This will return content only if stderr="|" was used. Otherwise, itwill throw an error.

Usage:process$read_all_error_lines()

Method write_input(): $write_input() writes the character vector (separated by sep) to thestandard input of the process. It will be converted to the specified encoding. This operation isnon-blocking, and it will return, even if the write fails (because the write buffer is full), or if itsuceeds partially (i.e. not the full string is written). It returns with a raw vector, that contains thebytes that were not written. You can supply this raw vector to $write_input() again, until it is fullywritten, and then the return value will be raw(0) (invisibly).

Usage:process$write_input(str, sep = "\n")

Arguments:

str Character or raw vector to write to the standard input of the process. If a character vectorwith a marked encoding, it will be converted to encoding.

sep Separator to add between str elements if it is a character vector. It is ignored if str is araw vector.

Returns: Leftover text (as a raw vector), that was not written.

Method get_input_file(): $get_input_file() if the stdin argument was a filename, this re-turns the absolute path to the file. If stdin was "|" or NULL, this simply returns that value.

Usage:process$get_input_file()

Method get_output_file(): $get_output_file() if the stdout argument was a filename, thisreturns the absolute path to the file. If stdout was "|" or NULL, this simply returns that value.

Usage:process$get_output_file()

Method get_error_file(): $get_error_file() if the stderr argument was a filename, thisreturns the absolute path to the file. If stderr was "|" or NULL, this simply returns that value.

Usage:process$get_error_file()

Page 17: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

process 17

Method poll_io(): $poll_io() polls the process’s connections for I/O. See more in the Pollingsection, and see also the poll() function to poll on multiple processes.

Usage:process$poll_io(timeout)

Arguments:

timeout Timeout in milliseconds, for the wait or the I/O polling.

Method get_poll_connection(): $get_poll_connetion() returns the poll connection, if theprocess has one.

Usage:process$get_poll_connection()

Method get_result(): $get_result() returns the result of the post processesing function. It canonly be called once the process has finished. If the process has no post-processing function, thenNULL is returned.

Usage:process$get_result()

Method as_ps_handle(): $as_ps_handle() returns a ps::ps_handle object, corresponding to theprocess.

Usage:process$as_ps_handle()

Method get_name(): Calls ps::ps_name() to get the process name.

Usage:process$get_name()

Method get_exe(): Calls ps::ps_exe() to get the path of the executable.

Usage:process$get_exe()

Method get_cmdline(): Calls ps::ps_cmdline() to get the command line.

Usage:process$get_cmdline()

Method get_status(): Calls ps::ps_status() to get the process status.

Usage:process$get_status()

Method get_username(): calls ps::ps_username() to get the username.

Usage:process$get_username()

Method get_wd(): Calls ps::ps_cwd() to get the current working directory.

Usage:

Page 18: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

18 run

process$get_wd()

Method get_cpu_times(): Calls ps::ps_cpu_times() to get CPU usage data.

Usage:

process$get_cpu_times()

Method get_memory_info(): Calls ps::ps_memory_info() to get memory data.

Usage:

process$get_memory_info()

Method suspend(): Calls ps::ps_suspend() to suspend the process.

Usage:

process$suspend()

Method resume(): Calls ps::ps_resume() to resume a suspended process.

Usage:

process$resume()

Examples

p <- process$new("sleep", "2")p$is_alive()pp$kill()p$is_alive()

p <- process$new("sleep", "1")p$is_alive()Sys.sleep(2)p$is_alive()

run Run external command, and wait until finishes

Description

run provides an interface similar to base::system() and base::system2(), but based on theprocess class. This allows some extra features, see below.

Page 19: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

run 19

Usage

run(command = NULL,args = character(),error_on_status = TRUE,wd = NULL,echo_cmd = FALSE,echo = FALSE,spinner = FALSE,timeout = Inf,stdout_line_callback = NULL,stdout_callback = NULL,stderr_line_callback = NULL,stderr_callback = NULL,stderr_to_stdout = FALSE,env = NULL,windows_verbatim_args = FALSE,windows_hide_window = FALSE,encoding = "",cleanup_tree = FALSE,...

)

Arguments

command Character scalar, the command to run.args Character vector, arguments to the command.error_on_status

Whether to throw an error if the command returns with a non-zero status, orit is interrupted. The error classes are system_command_status_error andsystem_command_timeout_error, respectively, and both errors have class system_command_erroras well. See also "Error conditions" below.

wd Working directory of the process. If NULL, the current working directory is used.echo_cmd Whether to print the command to run to the screen.echo Whether to print the standard output and error to the screen. Note that the order

of the standard output and error lines are not necessarily correct, as standardoutput is typically buffered.

spinner Whether to show a reassuring spinner while the process is running.timeout Timeout for the process, in seconds, or as a difftime object. If it is not finished

before this, it will be killed.stdout_line_callback

NULL, or a function to call for every line of the standard output. See stdout_callbackand also more below.

stdout_callback

NULL, or a function to call for every chunk of the standard output. A chunk canbe as small as a single character. At most one of stdout_line_callback andstdout_callback can be non-NULL.

Page 20: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

20 run

stderr_line_callback

NULL, or a function to call for every line of the standard error. See stderr_callbackand also more below.

stderr_callback

NULL, or a function to call for every chunk of the standard error. A chunk canbe as small as a single character. At most one of stderr_line_callback andstderr_callback can be non-NULL.

stderr_to_stdout

Whether to redirect the standard error to the standard output. Specifying TRUEhere will keep both in the standard output, correctly interleaved. However, it isnot possible to deduce where pieces of the output were coming from. If this isTRUE, the standard error callbacks (if any) are never called.

env Environment of the child process, a named character vector. IF NULL, the envi-ronment of the parent is inherited.

windows_verbatim_args

Whether to omit the escaping of the command and the arguments on windows.Ignored on other platforms.

windows_hide_window

Whether to hide the window of the application on windows. Ignored on otherplatforms.

encoding The encoding to assume for stdout and stderr. By default the encoding of thecurrent locale is used. Note that processx always reencodes the output of bothstreams in UTF-8 currently.

cleanup_tree Whether to clean up the child process tree after the process has finished.... Extra arguments are passed to process$new(), see process. Note that you can-

not pass stout or stderr here, because they are used internally by run(). Youcan use the stdout_callback, stderr_callback, etc. arguments to managethe standard output and error, or the process class directly if you need moreflexibility.

Details

run supports

• Specifying a timeout for the command. If the specified time has passed, and the process isstill running, it will be killed (with all its child processes).

• Calling a callback function for each line or each chunk of the standard output and/or error. Achunk may contain multiple lines, and can be as short as a single character.

• Cleaning up the subprocess, or the whole process tree, before exiting.

Value

A list with components:

• status The exit status of the process. If this is NA, then the process was killed and had no exitstatus.

• stdout The standard output of the command, in a character scalar.• stderr The standard error of the command, in a character scalar.• timeout Whether the process was killed because of a timeout.

Page 21: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

run 21

Callbacks

Some notes about the callback functions. The first argument of a callback function is a characterscalar (length 1 character), a single output or error line. The second argument is always the processobject. You can manipulate this object, for example you can call $kill() on it to terminate it, as aresponse to a message on the standard output or error.

Error conditions

run() throws error condition objects if the process is interrupted, timeouts or fails (if error_on_statusis TRUE):

• On interrupt, a condition with classes system_command_interrupt, interrupt, conditionis signalled. This can be caught with tryCatch(...,interrupt = ...).

• On timeout, a condition with classes system_command_timeout_error, system_command_error,error, condition is thrown.

• On error (if error_on_status is TRUE), an error with classes system_command_status_error,system_command_error, error, condition is thrown.

All of these conditions have the fields:

• message: the error message,

• stderr: the standard error of the process, or the standard output of the process if stderr_to_stdoutwas TRUE.

• call: the captured call to run().

• echo: the value of the echo argument.

• stderr_to_stdout: the value of the stderr_to_stdout argument.

• status: the exit status for system_command_status_error errors.

Examples

# This works on Unix systemsrun("ls")system.time(run("sleep", "10", timeout = 1, error_on_status = FALSE))system.time(

run("sh", c("-c", "for i in 1 2 3 4 5; do echo $i; sleep 1; done"),timeout = 2, error_on_status = FALSE

))

# This works on Windows systems, if the ping command is availablerun("ping", c("-n", "1", "127.0.0.1"))run("ping", c("-n", "6", "127.0.0.1"), timeout = 1,

error_on_status = FALSE)

Page 22: Package ‘processx’ · 2020. 7. 5. · ## S3 method for class ’processx_connection ... conn_read_chars() reads UTF-8 characters from the connections. If the connection itself

Index

base64_decode, 2base64_encode (base64_decode), 2base::normalizePath(), 10base::shQuote(), 10base::system(), 18base::system2(), 18

close.processx_connection(conn_create_fd), 2

conn_create_fd, 2conn_create_file (conn_create_fd), 2conn_create_pipepair (conn_create_fd), 2conn_disable_inheritance

(conn_create_fd), 2conn_get_fileno (conn_create_fd), 2conn_is_incomplete (conn_create_fd), 2conn_read_chars (conn_create_fd), 2conn_read_lines (conn_create_fd), 2conn_set_stderr (conn_create_fd), 2conn_set_stdout (conn_create_fd), 2conn_write (conn_create_fd), 2curl::multi_fdset(), 5curl_fds, 5

default_pty_options, 5default_pty_options(), 10

poll, 6poll(), 5, 7, 11, 17process, 7, 18, 20, 21processx_conn_close (conn_create_fd), 2processx_conn_is_incomplete

(conn_create_fd), 2processx_conn_read_chars

(conn_create_fd), 2processx_conn_read_lines

(conn_create_fd), 2processx_conn_write (conn_create_fd), 2ps::ps_cmdline(), 17ps::ps_cpu_times(), 18

ps::ps_cwd(), 17ps::ps_exe(), 17ps::ps_handle, 17ps::ps_memory_info(), 18ps::ps_name(), 17ps::ps_resume(), 18ps::ps_status(), 17ps::ps_suspend(), 18ps::ps_username(), 17

run, 18

tools::pskill(), 12

22