In the terminology of operating systems, a process is a space in which a program can execute. Emacs runs in a process. Emacs Lisp programs can invoke other programs in processes of their own. These are called subprocesses or child processes of the Emacs process, which is their parent process.
A subprocess of Emacs may be synchronous or asynchronous, depending on how it is created. When you create a synchronous subprocess, the Lisp program waits for the subprocess to terminate before continuing execution. When you create an asynchronous subprocess, it can run in parallel with the Lisp program. This kind of subprocess is represented within Emacs by a Lisp object which is also called a “process”. Lisp programs can use this object to communicate with the subprocess or to control it. For example, you can send signals, obtain status information, receive output from the process, or send input to it.
In addition to processes that run programs, Lisp programs can open connections of several types to devices or processes running on the same machine or on other machines. The supported connection types are: TCP and UDP network connections, serial port connections, and pipe connections. Each such connection is also represented by a process object.
This function returns t if object represents an Emacs
process object, nil otherwise. The process object can
represent a subprocess running a program or a connection of any
supported type.
In addition to subprocesses of the current Emacs session, you can also access other processes running on your machine. See Accessing Other Processes.
There are three primitives that create a new subprocess in which to run
a program. One of them, make-process, creates an asynchronous
process and returns a process object (see Creating an Asynchronous Process).
The other two, call-process and call-process-region,
create a synchronous process and do not return a process object
(see Creating a Synchronous Process). There are various higher-level
functions that make use of these primitives to run particular types of
process.
Synchronous and asynchronous processes are explained in the following sections. Since the three functions are all called in a similar fashion, their common arguments are described here.
In all cases, the functions specify the program to be run. An error
is signaled if the file is not found or cannot be executed. If the
file name is relative, the variable exec-path contains a list
of directories to search. Emacs initializes exec-path when it
starts up, based on the value of the environment variable PATH.
The standard file name constructs, ‘~’, ‘.’, and ‘..’,
are interpreted as usual in exec-path, but environment variable
substitutions (‘$HOME’, etc.) are not recognized; use
substitute-in-file-name to perform them (see Functions that Expand Filenames). nil in this list refers to
default-directory.
Executing a program can also try adding suffixes to the specified name:
This variable is a list of suffixes (strings) to try adding to the
specified program file name. The list should include "" if you
want the name to be tried exactly as specified. The default value is
system-dependent.
This function returns the connection-local value of variable
exec-suffixes.
Please note: The argument program contains only the name of the program file; it may not contain any command-line arguments. You must use a separate argument, args, to provide those, as described below.
Each of the subprocess-creating functions has a buffer-or-name
argument that specifies where the output from the program will go. It
should be a buffer or a buffer name; if it is a buffer name, that will
create the buffer if it does not already exist. It can also be
nil, which says to discard the output, unless a custom filter
function handles it. (See Process Filter Functions, and Reading and Printing Lisp Objects.) Normally, you should avoid having multiple processes send
output to the same buffer because their output would be intermixed
randomly. For synchronous processes, you can send the output to a
file instead of a buffer (and the corresponding argument is therefore
more appropriately called destination). By default, both
standard output and standard error streams go to the same destination,
but all the 3 primitives allow optionally to direct the standard error
stream to a different destination.
All three of the subprocess-creating functions allow specifying
command-line arguments for the process to run. For call-process
and call-process-region, these come in the form of a
&rest argument, args. For make-process, both the
program to run and its command-line arguments are specified as a list
of strings. The command-line arguments must all be strings, and they
are supplied to the program as separate argument strings. Wildcard
characters and other shell constructs have no special meanings in
these strings, since the strings are passed directly to the specified
program.
The subprocess inherits its environment from Emacs, but you can
specify overrides for it with process-environment. See Operating System Environment. The subprocess gets its current directory from the
value of default-directory.
The value of this variable is a string, the name of a directory that
contains programs that come with GNU Emacs and are intended for Emacs
to invoke. The program movemail is an example of such a program;
Rmail uses it to fetch new mail from an inbox.
The value of this variable is a list of directories to search for
programs to run in subprocesses. Each element is either the name of a
directory (i.e., a string), or nil, which stands for the default
directory (which is the value of default-directory).
See executable-find, for the details of this search.
The value of exec-path is used by call-process and
start-process when the program argument is not an absolute
file name.
Generally, you should not modify exec-path directly. Instead,
ensure that your PATH environment variable is set appropriately
before starting Emacs. Trying to modify exec-path
independently of PATH can lead to confusing results.
This function is an extension of the variable exec-path. If
default-directory indicates a remote directory, this function
returns a list of directories used for searching programs on the
respective remote host. In case of a local default-directory,
the function returns just the value of the variable exec-path.
If you use exec-suffixes together with this function, you must
also use the function exec-suffixes instead of the variable.
When starting a program that is part of the Emacs distribution, you must take into account that the program may have been renamed in order to comply with executable naming restrictions present on the system.
Instead of starting emacsclient, for example, you should specify
the value of emacsclient-program-name instead. Likewise, instead of
starting movemail, you must start
movemail-program-name, and the same goes for etags,
hexl, rcs2log, and
ebrowse.
Lisp programs sometimes need to run a shell and give it a command
that contains file names that were specified by the user. These
programs ought to be able to support any valid file name. But the shell
gives special treatment to certain characters, and if these characters
occur in the file name, they will confuse the shell. To handle these
characters, use the function shell-quote-argument:
This function returns a string that represents, in shell syntax, an argument whose actual contents are argument. It should work reliably to concatenate the return value into a shell command and then pass it to a shell for execution.
Precisely what this function does depends on your operating system. The function is designed to work with the syntax of your system’s standard shell; if you use an unusual shell, you will need to redefine this function. See Security Considerations.
;; This example shows the behavior on GNU and Unix systems. (shell-quote-argument "foo > bar") ⇒ "foo\\ \\>\\ bar" ;; This example shows the behavior on MS-DOS and MS-Windows. (shell-quote-argument "foo > bar") ⇒ "\"foo > bar\""
Here’s an example of using shell-quote-argument to construct
a shell command:
(concat "diff -u "
(shell-quote-argument oldfile)
" "
(shell-quote-argument newfile))
If the optional posix argument is non-nil, argument
is quoted according to POSIX shell quoting rules, regardless of the
system’s shell. This is useful when your shell could run on a remote
host, which requires a POSIX shell in general.
(shell-quote-argument "foo > bar" (file-remote-p default-directory))
The following two functions are useful for combining a list of
individual command-line argument strings into a single string, and
taking a string apart into a list of individual command-line
arguments. These functions are mainly intended for converting user
input in the minibuffer, a Lisp string, into a list of string
arguments to be passed to make-process, call-process or
start-process, or for converting such lists of arguments into a
single Lisp string to be presented in the minibuffer or echo area.
Note that if a shell is involved (e.g., if using
call-process-shell-command), arguments should still be
protected by shell-quote-argument;
combine-and-quote-strings is not intended to protect
special characters from shell evaluation.
This function splits string into substrings, respecting double and single quotes, as well as backslash quoting.
(split-string-shell-command "ls /tmp/'foo bar'")
⇒ ("ls" "/tmp/foo bar")
This function splits string into substrings at matches for the
regular expression separators, like split-string does
(see Creating Strings); in addition, it removes quoting from the
substrings. It then makes a list of the substrings and returns it.
If separators is omitted or nil, it defaults to
"\\s-+", which is a regular expression that matches one or more
characters with whitespace syntax (see Table of Syntax Classes).
This function supports two types of quoting: enclosing a whole string
in double quotes "…", and quoting individual characters
with a backslash escape ‘\’. The latter is also used in Lisp
strings, so this function can handle those as well.
This function concatenates list-of-strings into a single string,
quoting each string as necessary. It also sticks the separator
string between each pair of strings; if separator is omitted or
nil, it defaults to " ". The return value is the
resulting string.
The strings in list-of-strings that need quoting are those that
include separator as their substring. Quoting a string encloses
it in double quotes "…". In the simplest case, if you
are consing a command from the individual command-line arguments,
every argument that includes embedded blanks will be quoted.
Systems running Emacs impose a limit on the maximum total length of a command and its arguments submitted for execution. If a list of arguments to be processed by an external command might be arbitrarily long, then there is a risk of exceeding this limit, in which case executing the command will fail. In some cases this problem can be avoided by running the command multiple times on subsequent partitions of the list of arguments. When you know that it will not cause problems to run the command more than once, you can use this function to preemptively partition a list of arguments:
This function returns a list of subsequent partitions of arguments, a list of strings. command is a string or list of strings specifying the command to be run on arguments (unless shellp is non-nil, see below), and including any arguments that must be passed to every invocation of the command. Then, running a command formed of command plus any one of the returned partitions will not exceed the system’s limits on the maximum total length of a command and its arguments.
If optional argument shellp is non-nil, this function
implicitly includes shell-file-name and
shell-command-switch at the beginning of command
(see Creating an Asynchronous Process). In addition, in that case, this
function accounts for the extra length taken up by quoting and space
characters in its partitioning calculations.
On systems where the process-environment (see Operating System Environment) counts against command line length limits, this function
takes that into account too.
In the following example we impose an artificially small limit on
command line length and provide a fixed process-environment for
demonstration purposes. The partitioning of the list of arguments into
two sublists in the returned value implies that running cmd foo bar baz on this hypothetical system would exceed system limits, and
thus fail. The calling code should run cmd twice, on each of the
two partitions, so cmd foo bar and then cmd baz.
(let ((system-type 'gnu/linux)
(command-line-max-length 20)
(process-environment '("BLAH=blah")))
(multiple-command-partition-arguments "cmd" '("foo" "bar" "baz")))
⇒ (("foo" "bar") ("baz"))
This function takes a conservative approach and does not try to minimize the number of partitions of arguments, because doing that would require a great deal of platform-specific information, and also information about encoding which is not currently made available to Lisp.
This variable holds the maximum length of a command and its arguments on
this system, measured in characters, as used by
multiple-command-partition-arguments.
After a synchronous process is created, Emacs waits for the
process to terminate before continuing. Starting Dired on GNU or
Unix31 is an example of this: it
runs ls in a synchronous process, then modifies the output
slightly. Because the process is synchronous, the entire directory
listing arrives in the buffer before Emacs tries to do anything with it.
While Emacs waits for the synchronous subprocess to terminate, the
user can quit by typing C-g. The first C-g tries to kill
the subprocess with a SIGINT signal; but it waits until the
subprocess actually terminates before quitting. If during that time the
user types another C-g, that kills the subprocess instantly with
SIGKILL and quits immediately (except on MS-DOS, where killing
other processes doesn’t work). See Quitting.
The synchronous subprocess functions return an indication of how the process terminated.
The output from a synchronous subprocess is generally decoded using a
coding system, much like text read from a file. The input sent to a
subprocess by call-process-region is encoded using a coding
system, much like text written into a file. See Coding Systems.
This function calls program and waits for it to finish.
The current working directory of the subprocess is set to the current
buffer’s value of default-directory if that is local (as
determined by unhandled-file-name-directory), or "~" otherwise.
If you want to run a process in a remote directory use
process-file.
The standard input for the new process comes from file infile if
infile is not nil, and from the null device otherwise.
The argument destination says where to put the process output.
Here are the possibilities:
Insert the output in that buffer, before point. This includes both the standard output stream and the standard error stream of the process.
Insert the output in a buffer with that name, before point.
tInsert the output in the current buffer, before point.
nilDiscard the output.
Discard the output, and return nil immediately without waiting
for the subprocess to finish.
In this case, the process is not truly synchronous, since it can run in parallel with Emacs; but you can think of it as synchronous in that Emacs is essentially finished with the subprocess as soon as this function returns.
MS-DOS doesn’t support asynchronous subprocesses, so this option doesn’t work there.
(:file file-name)Send the output to the file name specified, overwriting it if it already exists.
(real-destination error-destination)Keep the standard output stream separate from the standard error stream;
deal with the ordinary output as specified by real-destination,
and dispose of the error output according to error-destination.
If error-destination is nil, that means to discard the
error output, t means mix it with the ordinary output, and a
string specifies a file name to redirect error output into.
You can’t directly specify a buffer to put the error output in; that is too difficult to implement. But you can achieve this result by sending the error output to a temporary file and then inserting the file into a buffer when the subprocess finishes.
If display is non-nil, then call-process redisplays
the buffer as output is inserted. (However, if the coding system chosen
for decoding output is undecided, meaning deduce the encoding
from the actual data, then redisplay sometimes cannot continue once
non-ASCII characters are encountered. There are fundamental
reasons why it is hard to fix this; see Receiving Output from Processes.)
Otherwise the function call-process does no redisplay, and the
results become visible on the screen only when Emacs redisplays that
buffer in the normal course of events.
The remaining arguments, args, are strings that specify command line arguments for the program. Each string is passed to program as a separate argument.
The value returned by call-process (unless you told it not to
wait) indicates the reason for process termination. A number gives the
exit status of the subprocess; 0 means success, and any other value
means failure. If the process terminated with a signal,
call-process returns a string describing the signal. If you
told call-process not to wait, it returns nil.
In the examples below, the buffer ‘foo’ is current.
(call-process "pwd" nil t)
⇒ 0
---------- Buffer: foo ----------
/home/lewis/manual
---------- Buffer: foo ----------
(call-process "grep" nil "bar" nil "lewis" "/etc/passwd")
⇒ 0
---------- Buffer: bar ----------
lewis:x:1001:1001:Bil Lewis,,,,:/home/lewis:/bin/bash
---------- Buffer: bar ----------
Here is an example of the use of call-process, as used to
be found in the definition of the insert-directory function:
(call-process insert-directory-program nil t nil switches
(if full-directory-p
(concat (file-name-as-directory file) ".")
file))
This function processes files synchronously in a separate process. It
is similar to call-process, but may invoke a file name handler
based on the value of the variable default-directory, which
specifies the current working directory of the subprocess.
The arguments are handled in almost the same way as for
call-process, with the following differences:
Some file name handlers may not support all combinations and forms of the
arguments infile, buffer, and display. For example,
some file name handlers might behave as if display were nil,
regardless of the value actually passed. As another example, some
file name handlers might not support separating standard output and error
output by way of the buffer argument.
If a file name handler is invoked, it determines the program to run based
on the first argument program. For instance, suppose that a
handler for remote files is invoked. Then the path that is used for
searching for the program might be different from exec-path.
The second argument infile may invoke a file name handler. The file
name handler could be different from the handler chosen for the
process-file function itself. (For example,
default-directory could be on one remote host, and
infile on a different remote host. Or default-directory
could be non-special, whereas infile is on a remote host.)
If buffer is a list of the form (real-destination
error-destination), and error-destination names a file,
then the same remarks as for infile apply.
The remaining arguments (args) will be passed to the process
verbatim. Emacs is not involved in processing file names that are
present in args. To avoid confusion, it may be best to avoid
absolute file names in args, but rather to specify all file
names as relative to default-directory. The function
file-relative-name is useful for constructing such relative
file names. Alternatively, you can use file-local-name
(see Making Certain File Names “Magic”) to obtain an absolute file name as seen
from the remote host’s perspective.
This variable indicates whether a call of process-file changes
remote files.
By default, this variable is always set to t, meaning that a
call of process-file could potentially change any file on a
remote host. When set to nil, a file name handler could optimize
its behavior with respect to remote file attribute caching.
You should only ever change this variable with a let-binding; never
with setq.
This user option indicates whether a call of process-file
returns a string describing the signal interrupting a remote process.
When a process returns an exit code greater than 128, it is
interpreted as a signal. process-file requires returning a
string describing this signal.
Since there are processes violating this rule, returning exit codes
greater than 128 which are not bound to a signal, process-file
returns always the exit code as natural number for remote processes.
Setting this user option to non-nil forces process-file to
interpret such exit codes as signals, and to return a corresponding
string.
This function sends the text from start to end as
standard input to a process running program. It deletes the text
sent if delete is non-nil; this is useful when
destination is t, to insert the output in the current
buffer in place of the input.
The arguments destination and display control what to do
with the output from the subprocess, and whether to update the display
as it comes in. For details, see the description of
call-process, above. If destination is the integer 0,
call-process-region discards the output and returns nil
immediately, without waiting for the subprocess to finish (this only
works if asynchronous subprocesses are supported; i.e., not on MS-DOS).
The remaining arguments, args, are strings that specify command line arguments for the program.
The return value of call-process-region is just like that of
call-process: nil if you told it to return without
waiting; otherwise, a number or string which indicates how the
subprocess terminated.
In the following example, we use call-process-region to run the
cat utility, with standard input being the first five characters
in buffer ‘foo’ (the word ‘input’). cat copies its
standard input into its standard output. Since the argument
destination is t, this output is inserted in the current
buffer.
---------- Buffer: foo ---------- input∗ ---------- Buffer: foo ----------
(call-process-region 1 6 "cat" nil t)
⇒ 0
---------- Buffer: foo ----------
inputinput∗
---------- Buffer: foo ----------
For example, the shell-command-on-region command uses
call-shell-region in a manner similar to this:
(call-shell-region
start end
command ; shell command
nil ; do not delete region
buffer) ; send output to buffer
This function executes the shell command command synchronously.
The other arguments are handled as in call-process. An old
calling convention allowed passing any number of additional arguments
after display, which were concatenated to command; this is
still supported, but strongly discouraged.
This function is like call-process-shell-command, but uses
process-file internally. Depending on default-directory,
command can be executed also on remote hosts. An old calling
convention allowed passing any number of additional arguments after
display, which were concatenated to command; this is still
supported, but strongly discouraged.
This function sends the text from start to end as
standard input to an inferior shell running command. This function
is similar than call-process-region, with process being a shell.
The arguments delete, destination and the return value
are like in call-process-region.
Note that this function doesn’t accept additional arguments.
If command names a shell (e.g., via shell-file-name), keep
in mind that behavior of various shells when commands are piped to their
standard input is shell- and system-dependent, and thus non-portable.
The differences are especially prominent when the region includes more
than one line, i.e. when piping to a shell commands with embedded
newlines. Lisp programs using this technique will therefore need to
format the text in the region differently, according to the expectations
of the shell.
This function executes command (a string) as a shell command,
then returns the command’s output as a string. If command
actually includes more than one command, the behavior depends on the
shell to be invoked (determined by shell-file-name for local
commands). In particular, the separator between the commands cannot be
a newline on MS-Windows; use ‘&&’ instead.
This function runs program, waits for it to finish, and returns its output as a list of strings. Each string in the list holds a single line of text output by the program; the end-of-line characters are stripped from each line. The arguments beyond program, args, are strings that specify command-line arguments with which to run the program.
If program exits with a non-zero exit status, this function signals an error.
This function works by calling call-process, so program output
is decoded in the same way as for call-process.
This function is just like process-lines, but does not signal
an error if program exits with a non-zero exit status.
In this section, we describe how to create an asynchronous process. After an asynchronous process is created, it runs in parallel with Emacs, and Emacs can communicate with it using the functions described in the following sections (see Sending Input to Processes, and see Receiving Output from Processes). Note that process communication is only partially asynchronous: Emacs sends and receives data to and from a process only when those functions are called.
An asynchronous process is controlled either via a pty
(pseudo-terminal) or a pipe. The choice of pty or pipe is made
when creating the process, by default based on the value of the
variable process-connection-type (see below). If available,
ptys are usually preferable for processes visible to the user, as in
Shell mode, because they allow for job control (C-c, C-z,
etc.) between the process and its children, and because interactive
programs treat ptys as terminal devices, whereas pipes don’t support
these features. However, for subprocesses used by Lisp programs for
internal purposes (i.e., no user interaction with the subprocess is
required), where significant amounts of data need to be exchanged
between the subprocess and the Lisp program, it is often better to use
a pipe, because pipes are more efficient. Also, the total number of
ptys is limited on many systems, and it is good not to waste them
unnecessarily.
This function is the basic low-level primitive for starting
asynchronous subprocesses. It returns a process object representing
the subprocess. Compared to the more high-level start-process,
described below, it takes keyword arguments, is more flexible, and
enables you to specify process filters and sentinels in a single call.
The arguments args are a list of keyword/argument pairs.
Omitting a keyword is always equivalent to specifying it with value
nil. Here are the meaningful keywords:
:name nameUse the string name as the process name; if a process with this name already exists, then name is modified (by appending ‘<1>’, etc.) to be unique.
:buffer bufferUse buffer as the process buffer. If the value is nil,
the subprocess is not associated with any buffer.
:command commandUse command as the command line of the process. The value
should be a list starting with the program’s executable file name,
followed by strings to give to the program as its arguments. If
the first element of the list is nil, Emacs opens a new
pseudoterminal (pty) and associates its input and output with
buffer, without actually running any program; the rest of the
list elements are ignored in that case.
:coding codingIf coding is a symbol, it specifies the coding system to be
used for both reading and writing of data from and to the
connection. If coding is a cons cell
(decoding . encoding), then decoding
will be used for reading and encoding for writing. The coding
system used for encoding the data written to the program is also used
for encoding the command-line arguments (but not the program itself,
whose file name is encoded as any other file name; see file-name-coding-system).
If coding is nil, the default rules for finding the
coding system will apply. See Default Coding Systems.
:connection-type typeInitialize the type of device used to communicate with the subprocess.
Possible values are pty to use a pty, pipe to use a
pipe, or nil to use the default derived from the value of the
process-connection-type variable. If type is a cons cell
(input . output), then input will be used
for standard input and output for standard output (and standard
error if :stderr is nil).
On systems where ptys are not available (MS-Windows), this parameter is ignored, and pipes are used unconditionally.
:noquery query-flagInitialize the process query flag to query-flag. See Querying Before Exit.
:stop stoppedIf provided, stopped must be nil; it is an error to use
any non-nil value. The :stop key is ignored otherwise
and is retained for compatibility with other process types such as
pipe processes. Asynchronous subprocesses never start in the stopped
state.
:filter filterInitialize the process filter to filter. If not specified, a default filter will be provided, which can be overridden later. See Process Filter Functions.
:sentinel sentinelInitialize the process sentinel to sentinel. If not specified, a default sentinel will be used, which can be overridden later. See Sentinels: Detecting Process Status Changes.
:stderr stderrAssociate stderr with the standard error of the process. A
non-nil value should be either a buffer or a pipe process
created with make-pipe-process, described below. If
stderr is nil, standard error is mixed with standard
output, and both are sent to buffer or filter.
If stderr is a buffer, Emacs will create a pipe process, the
standard error process. This process will have the default
filter (see Process Filter Functions), sentinel (see Sentinels: Detecting Process Status Changes), and
coding systems (see Default Coding Systems). On the other hand,
it will use query-flag as its query-on-exit flag (see Querying Before Exit). It will be associated with the stderr buffer
(see Process Buffers) and send its output (which is the standard
error of the main process) there. To get the process object for the
standard error process, pass the stderr buffer to
get-buffer-process.
If stderr is a pipe process, Emacs will use it as standard error process for the new process.
:file-handler file-handlerIf file-handler is non-nil, then look for a file name
handler for the current buffer’s default-directory, and invoke
that file name handler to make the process. If there is no such
handler, proceed as if file-handler were nil.
The original argument list, modified with the actual connection
information, is available via the process-contact function.
The current working directory of the subprocess is set to the current
buffer’s value of default-directory if that is local (as
determined by unhandled-file-name-directory), or ~
otherwise. If you want to run a process in a remote directory, pass
:file-handler t to make-process. In that case, the
current working directory is the local name component of
default-directory (as determined by file-local-name).
Depending on the implementation of the file name handler, it might not
be possible to apply filter or sentinel to the resulting
process object. The :stderr argument cannot be a pipe process,
file name handlers do not support pipe processes for this. A buffer
as :stderr argument is accepted, its contents is shown without
the use of pipe processes. See Process Filter Functions, Sentinels: Detecting Process Status Changes,
and Accepting Output from Processes.
Some file name handlers may not support make-process. In such
cases, this function does nothing and returns nil.
This function creates a bidirectional pipe which can be attached to a
child process. This is useful with the :stderr keyword of
make-process. The function returns a process object.
The arguments args are a list of keyword/argument pairs.
Omitting a keyword is always equivalent to specifying it with value
nil.
Here are the meaningful keywords:
:name nameUse the string name as the process name. As with
make-process, it is modified if necessary to make it unique.
:buffer bufferUse buffer as the process buffer. If the value is nil,
the subprocess is not associated with any buffer.
:coding codingIf coding is a symbol, it specifies the coding system to be
used for both reading and writing of data from and to the
connection. If coding is a cons cell
(decoding . encoding), then decoding
will be used for reading and encoding for writing.
If coding is nil, the default rules for finding the
coding system will apply. See Default Coding Systems.
:noquery query-flagInitialize the process query flag to query-flag. See Querying Before Exit.
:stop stoppedIf stopped is non-nil, start the process in the stopped
state. In the stopped state, a pipe process does not accept incoming
data, but you can send outgoing data. The stopped state is set by
stop-process and cleared by continue-process
(see Sending Signals to Processes).
:filter filterInitialize the process filter to filter. If not specified, a default filter will be provided, which can be changed later. See Process Filter Functions.
:sentinel sentinelInitialize the process sentinel to sentinel. If not specified, a default sentinel will be used, which can be changed later. See Sentinels: Detecting Process Status Changes.
The original argument list, modified with the actual connection
information, is available via the process-contact function.
This function is a higher-level wrapper around make-process,
exposing an interface that is similar to call-process. It
creates a new asynchronous subprocess and starts the specified
program running in it. It returns a process object that stands
for the new subprocess in Lisp. The argument name specifies the
name for the process object; as with make-process, it is
modified if necessary to make it unique. The buffer
buffer-or-name is the buffer to associate with the process.
If program is nil, Emacs opens a new pseudoterminal (pty)
and associates its input and output with buffer-or-name, without
creating a subprocess. In that case, the remaining arguments
args are ignored.
The rest of args are strings that specify command line arguments for the subprocess.
In the example below, the first process is started and runs (rather, sleeps) for 100 seconds (the output buffer ‘foo’ is created immediately). Meanwhile, the second process is started, and given the name ‘my-process<1>’ for the sake of uniqueness. It inserts the directory listing at the end of the buffer ‘foo’, before the first process finishes. Then it finishes, and a message to that effect is inserted in the buffer. Much later, the first process finishes, and another message is inserted in the buffer for it.
(start-process "my-process" "foo" "sleep" "100")
⇒ #<process my-process>
(start-process "my-process" "foo" "ls" "-l" "/bin")
⇒ #<process my-process<1>>
---------- Buffer: foo ----------
total 8336
-rwxr-xr-x 1 root root 971384 Mar 30 10:14 bash
-rwxr-xr-x 1 root root 146920 Jul 5 2011 bsd-csh
...
-rwxr-xr-x 1 root root 696880 Feb 28 15:55 zsh4
Process my-process<1> finished
Process my-process finished
---------- Buffer: foo ----------
Like start-process, this function starts a new asynchronous
subprocess running program in it, and returns its process
object.
The difference from start-process is that this function may
invoke a file name handler based on the value of default-directory.
This handler ought to run program, perhaps on the local host,
perhaps on a remote host that corresponds to default-directory.
In the latter case, the local part of default-directory becomes
the working directory of the process.
This function does not try to invoke file name handlers for
program or for the rest of args. For that reason, if
program or any of args use the remote-file syntax
(see Making Certain File Names “Magic”), they must be converted either to file
names relative to default-directory, or to names that identify
the files locally on the remote host, by running them through
file-local-name.
Depending on the implementation of the file name handler, it might not be
possible to apply process-filter or process-sentinel to
the resulting process object. See Process Filter Functions, and Sentinels: Detecting Process Status Changes.
Some file name handlers may not support start-file-process (for
example the function ange-ftp-hook-function). In such cases,
this function does nothing and returns nil.
This function is like start-process, except that it uses a
shell to execute the specified command. The argument
command is a shell command string. The variable
shell-file-name specifies which shell to use.
The point of running a program through the shell, rather than directly
with make-process or start-process, is so that you can
employ shell features such as wildcards in the arguments. It follows
that if you include any arbitrary user-specified arguments in the
command, you should quote them with shell-quote-argument first,
so that any special shell characters do not have their special
shell meanings. See Shell Arguments. Of course, when executing
commands based on user input you should also consider the security
implications.
This function is like start-process-shell-command, but uses
start-file-process internally. Because of this, command
can also be executed on remote hosts, depending on default-directory.
This variable controls the type of device used to communicate with
asynchronous subprocesses. If it is non-nil, then ptys are
used, when available. Otherwise, pipes are used.
The value of process-connection-type takes effect when
make-process or start-process is called. So you can
specify how to communicate with one subprocess by binding the variable
around the call to these functions.
Note that the value of this variable is ignored when
make-process is called with a non-nil value of the
:stderr parameter; in that case, Emacs will communicate with
the process using pipes. It is also ignored if ptys are unavailable
(MS-Windows).
(let ((process-connection-type nil)) ; use a pipe
(start-process ...))
To determine whether a given subprocess actually got a pipe or a pty,
use the function process-tty-name (see Process Information).
If a process sentinel/filter function has an error, Emacs will (by
default) pause Emacs for process-error-pause-time seconds after
displaying this error, so that users will see the error in question.
However, this can lead to situations where Emacs becomes unresponsive
(if there’s a lot of these errors happening), so this can be disabled
by setting process-error-pause-time to 0.
Deleting a process disconnects Emacs immediately from the subprocess. Processes are deleted automatically after they terminate, but not necessarily right away. You can delete a process explicitly at any time. If you explicitly delete a terminated process before it is deleted automatically, no harm results. Deleting a running process sends a signal to terminate it (and its child processes, if any), and calls the process sentinel. See Sentinels: Detecting Process Status Changes.
When a process is deleted, the process object itself continues to exist as long as other Lisp objects point to it. All the Lisp primitives that work on process objects accept deleted processes, but those that do I/O or send signals will report an error. The process mark continues to point to the same place as before, usually into a buffer where output from the process was being inserted.
This variable controls automatic deletion of processes that have
terminated (due to calling exit or to a signal). If it is
nil, then they continue to exist until the user runs
list-processes. Otherwise, they are deleted immediately after
they exit.
This function deletes a process, killing it with a SIGKILL
signal if the process was running a program. The argument may be a
process, the name of a process, a buffer, or the name of a buffer. (A
buffer or buffer-name stands for the process that
get-buffer-process returns, and a missing or nil
process means that the current buffer’s process should be
killed.) Calling delete-process on a running process
terminates it, updates the process status, and runs the sentinel
immediately. If the process has already terminated, calling
delete-process has no effect on its status, or on the running
of its sentinel (which will happen sooner or later).
If the process object represents a network, serial, or pipe
connection, its status changes to closed; otherwise, it changes
to signal, unless the process already exited. See process-status.
(delete-process "*shell*")
⇒ nil
Several functions return information about processes.
This command displays a listing of all living processes. In addition,
it finally deletes any process whose status was ‘Exited’ or
‘Signaled’. It returns nil.
The processes are shown in a buffer named *Process List* (unless you specify otherwise using the optional argument buffer), whose major mode is Process Menu mode.
If query-only is non-nil, it only lists processes
whose query flag is non-nil. See Querying Before Exit.
This function returns a list of all processes that have not been deleted.
(process-list)
⇒ (#<process display-time> #<process shell>)
This function returns the number of processors, a positive integer.
Each usable thread execution unit counts as a processor.
By default, the count includes the number of available processors,
which you can override by setting the
OMP_NUM_THREADS environment variable of OpenMP.
If the optional argument query is current,
this function ignores OMP_NUM_THREADS;
if query is all, this function also counts processors
that are on the system but are not available to the current process.
This function returns the process named name (a string), or
nil if there is none. The argument name can also be a
process object, in which case it is returned.
(get-process "shell")
⇒ #<process shell>
This function returns the command that was executed to start
process. This is a list of strings, the first string being the
program executed and the rest of the strings being the arguments that
were given to the program. For a network, serial, or pipe connection,
this is either nil, which means the process is running or
t (process is stopped).
(process-command (get-process "shell"))
⇒ ("bash" "-i")
This function returns information about how a network, a serial, or a
pipe connection was set up. When key is nil, it returns
(hostname service) for a network connection,
(port speed) for a serial connection, and t
for a pipe connection. For an ordinary child process, this function
always returns t when called with a nil key.
If key is t, the value is the complete status information
for the connection, server, serial port, or pipe; that is, the list of
keywords and values specified in make-network-process,
make-serial-process, or make-pipe-process, except that
some of the values represent the current status instead of what you
specified.
For a network process, the values include (see
make-network-process for a complete list):
:bufferThe associated value is the process buffer.
:filterThe associated value is the process filter function. See Process Filter Functions.
:sentinelThe associated value is the process sentinel function. See Sentinels: Detecting Process Status Changes.
:remoteIn a connection, the address in internal format of the remote peer.
:localThe local address, in internal format.
:serviceIn a server, if you specified t for service,
this value is the actual port number.
:local and :remote are included even if they were not
specified explicitly in make-network-process.
For a serial connection, see make-serial-process and
serial-process-configure for the list of keys. For a pipe
connection, see make-pipe-process for the list of keys.
If key is a keyword, the function returns the value corresponding to that keyword.
If process is a non-blocking network stream that hasn’t been
fully set up yet, then this function will block until that has
happened. If given the optional no-block parameter, this
function will return nil instead of blocking.
This function returns the PID of process. This is an
integral number that distinguishes the process process from all
other processes running on the same computer at the current time. The
PID of a process is chosen by the operating system kernel
when the process is started and remains constant as long as the
process exists. For network, serial, and pipe connections, this
function returns nil.
This function returns the name of process, as a string.
This function returns the status of process-name as a symbol. The argument process-name must be a process, a buffer, or a process name (a string).
The possible values for an actual subprocess are:
runfor a process that is running.
stopfor a process that is stopped but continuable.
exitfor a process that has exited.
signalfor a process that has received a fatal signal.
openfor a network, serial, or pipe connection that is open.
closedfor a network, serial, or pipe connection that is closed. Once a connection is closed, you cannot reopen it, though you might be able to open a new connection to the same place.
connectfor a non-blocking connection that is waiting to complete.
failedfor a non-blocking connection that has failed to complete.
listenfor a network server that is listening.
nilif process-name is not the name of an existing process.
(process-status (get-buffer "*shell*"))
⇒ run
For a network, serial, or pipe connection, process-status
returns one of the symbols open, stop, or closed.
The latter means that the other side closed the connection, or Emacs
did delete-process. The value stop means that
stop-process was called on the connection.
This function returns non-nil if process is alive. A
process is considered alive if its status is run, open,
listen, connect or stop.
This function returns the symbol network for a network
connection or server, serial for a serial port connection,
pipe for a pipe connection, or real for a subprocess
created for running a program.
This function returns the exit status of process or the signal
number that killed it. (Use the result of process-status to
determine which of those it is.) If process has not yet
terminated, the value is 0. For network, serial, and pipe connections
that are already closed, the value is either 0 or 256, depending on
whether the connection was closed normally or abnormally.
This function returns the terminal name that process is using for
its communication with Emacs—or nil if it is using pipes
instead of a pty (see process-connection-type in
Creating an Asynchronous Process). By default, this function returns the
terminal name if any of process’s standard streams use a
terminal. If stream is one of stdin, stdout, or
stderr, this function returns the terminal name (or nil,
as above) that process uses for that stream specifically. You
can use this to determine whether a particular stream uses a pipe or a
pty.
If process represents a program running on a remote host, this
function returns the local terminal name that communicates with
process; you can get the terminal name used by that program on
the remote host with the process property remote-tty. If
process represents a network, serial, or pipe connection, this
function always returns nil.
This function returns a cons cell (decode . encode),
describing the coding systems in use for decoding output from, and
encoding input to, process (see Coding Systems).
This function specifies the coding systems to use for subsequent output from and input to process. It will use decoding-system to decode subprocess output, and encoding-system to encode subprocess input.
Every process also has a property list that you can use to store miscellaneous values associated with the process.
This function returns the value of the propname property of process.
This function sets the value of the propname property of process to value.
This function returns the process plist of process.
This function sets the process plist of process to plist.
Asynchronous subprocesses receive input when it is sent to them by Emacs, which is done with the functions in this section. You must specify the process to send input to, and the input data to send. If the subprocess runs a program, the data appears on the standard input of that program; for connections, the data is sent to the connected device or program.
Some operating systems have limited space for buffered input in a pty. On these systems, Emacs sends an EOF periodically amidst the other characters, to force them through. For most programs, these EOFs do no harm.
Subprocess input is normally encoded using a coding system before the
subprocess receives it, much like text written into a file. You can use
set-process-coding-system to specify which coding system to use
(see Process Information). Otherwise, the coding system comes from
coding-system-for-write, if that is non-nil; or else from
the defaulting mechanism (see Default Coding Systems).
Sometimes the system is unable to accept input for that process, because the input buffer is full. When this happens, the send functions wait a short while, accepting output from subprocesses, and then try again. This gives the subprocess a chance to read more of its pending input and make space in the buffer. It also allows filters (including the one currently running), sentinels and timers to run—so take account of that in writing your code.
In these functions, the process argument can be a process or
the name of a process, or a buffer or buffer name (which stands
for a process via get-buffer-process). nil means
the current buffer’s process.
This function sends process the contents of string as
standard input. It returns nil. For example, to make a
Shell buffer list files:
(process-send-string "shell<1>" "ls\n")
⇒ nil
This function sends the text in the region defined by start and end as standard input to process.
An error is signaled unless both start and end are integers or markers that indicate positions in the current buffer. (It is unimportant which number is larger.)
This function makes process see an end-of-file in its input. The EOF comes after any text already sent to it. The function returns process.
(process-send-eof "shell")
⇒ "shell"
This function will tell you whether a process, which must not be
a connection but a real subprocess, has given control of its terminal
to a child process of its own. If this is true, the function returns
the numeric ID of the foreground process group of process; it
returns nil if Emacs can be certain that this is not so. The
value is t if Emacs cannot tell whether this is true. This
function signals an error if process is a network, serial, or
pipe connection, or if the subprocess is not active.
Sending a signal to a subprocess is a way of interrupting its
activities. There are several different signals, each with its own
meaning. The set of signals and their names is defined by the operating
system. For example, the signal SIGINT means that the user has
typed C-c, or that some analogous thing has happened.
Each signal has a standard effect on the subprocess. Most signals kill the subprocess, but some stop (or resume) execution instead. Most signals can optionally be handled by programs; if the program handles the signal, then we can say nothing in general about its effects.
You can send signals explicitly by calling the functions in this
section. Emacs also sends signals automatically at certain times:
killing a buffer sends a SIGHUP signal to all its associated
processes; killing Emacs sends a SIGHUP signal to all remaining
processes. (SIGHUP is a signal that usually indicates that the
user “hung up the phone”, i.e., disconnected.)
Each of the signal-sending functions takes two optional arguments: process and current-group.
The argument process must be either a process, a process
name, a buffer, a buffer name, or nil. A buffer or buffer name
stands for a process through get-buffer-process. nil
stands for the process associated with the current buffer. Except
with stop-process and continue-process, an error is
signaled if process does not identify an active process, or if
it represents a network, serial, or pipe connection.
The argument current-group is a flag that makes a difference
when you are running a job-control shell as an Emacs subprocess. If it
is non-nil, then the signal is sent to the current process-group
of the terminal that Emacs uses to communicate with the subprocess. If
the process is a job-control shell, this means the shell’s current
subjob. If current-group is nil, the signal is
sent to the process group of the immediate subprocess of Emacs. If
the subprocess is a job-control shell, this is the shell itself. If
current-group is lambda, the signal is sent to the
process-group that owns the terminal, but only if it is not the shell
itself.
The flag current-group has no effect when a pipe is used to
communicate with the subprocess, because the operating system does not
support the distinction in the case of pipes. For the same reason,
job-control shells won’t work when a pipe is used. See
process-connection-type in Creating an Asynchronous Process.
This function interrupts the process process by sending the
signal SIGINT. Outside of Emacs, typing the interrupt
character (normally C-c on some systems, and DEL on
others) sends this signal. When the argument current-group is
non-nil, you can think of this function as typing C-c
on the terminal by which Emacs talks to the subprocess.
This command kills the process process by sending the
signal SIGKILL. This signal kills the subprocess immediately,
and cannot be handled by the subprocess. Interactively, it’ll prompt
the user for a process name, defaulting to the process (if any) in the
current buffer.
This function sends the signal SIGQUIT to the process
process. This signal is the one sent by the quit
character (usually C-\) when you are not inside
Emacs.
This function stops the specified process. If it is a real
subprocess running a program, it sends the signal SIGTSTP to
that subprocess. If process represents a network, serial, or
pipe connection, this function inhibits handling of the incoming data
from the connection; for a network server, this means not accepting
new connections. Use continue-process to resume normal
execution.
Outside of Emacs, on systems with job control, the stop character
(usually C-z) normally sends the SIGTSTP signal to a
subprocess. When current-group is non-nil, you can think
of this function as typing C-z on the terminal Emacs uses to
communicate with the subprocess.
This function resumes execution of the process process. If it
is a real subprocess running a program, it sends the signal
SIGCONT to that subprocess; this presumes that process
was stopped previously. If process represents a network,
serial, or pipe connection, this function resumes handling of the
incoming data from the connection. For serial connections, data that
arrived during the time the process was stopped might be lost.
This function sends a signal to process process. The argument signal specifies which signal to send; it should be an integer, or a symbol whose name is a signal.
The process argument can be a system process ID (an integer); that allows you to send signals to processes that are not children of Emacs. See Accessing Other Processes.
If process is a process object which contains the property
remote-pid, or process is a number and remote is a
remote file name, process is interpreted as process on the
respective remote host, which will be the process to signal.
If process is a string, it is interpreted as process object with the respective process name, or as a number.
Sometimes, it is necessary to send a signal to a non-local
asynchronous process. This is possible by writing an own
interrupt-process or signal-process implementation.
This function must be added then to interrupt-process-functions
or signal-process-functions, respectively.
This variable is a list of functions to be called for
interrupt-process. The arguments of the functions are the same
as for interrupt-process. These functions are called in the
order of the list, until one of them returns non-nil. The
default function, which shall always be the last in this list, is
internal-default-interrupt-process.
This is the mechanism, how Tramp implements interrupt-process.
This variable is a list of functions to be called for
signal-process. The arguments of the functions are the same as
for signal-process. These functions are called in the order of
the list, until one of them returns non-nil. The default
function, which shall always be the last in this list, is
internal-default-signal-process.
This is the mechanism, how Tramp implements signal-process.
The output that an asynchronous subprocess writes to its standard output stream is passed to a function called the filter function. The default filter function simply inserts the output into a buffer, which is called the associated buffer of the process (see Process Buffers). If the process has no buffer then the default filter discards the output.
If the subprocess writes to its standard error stream, by default
the error output is also passed to the process filter function.
Alternatively, you could use the :stderr parameter with a
non-nil value in a call to make-process
(see make-process) to make the destination
of the error output separate from the standard output.
When a subprocess terminates, Emacs reads any pending output, then stops reading output from that subprocess. Therefore, if the subprocess has children that are still live and still producing output, Emacs won’t receive that output.
Output from a subprocess can arrive only while Emacs is waiting: when
reading terminal input (see the function waiting-for-user-input-p),
in sit-for and sleep-for (see Waiting for Elapsed Time or Input), in
accept-process-output (see Accepting Output from Processes), and in
functions which send data to processes (see Sending Input to Processes).
This minimizes the problem of timing errors that usually plague parallel
programming. For example, you can safely create a process and only
then specify its buffer or filter function; no output can arrive
before you finish, if the code in between does not call any primitive
that waits.
On some systems, when Emacs reads the output from a subprocess, the
output data is read in very small blocks, potentially resulting in
very poor performance. This behavior can be remedied to some extent
by setting the variable process-adaptive-read-buffering to a
non-nil value, as it will automatically delay reading
from such processes, thus allowing them to produce more output before
Emacs tries to read it. The default is nil, since a
non-nil value reduces performance.
A process can (and usually does) have an associated buffer, which is an ordinary Emacs buffer that is used for two purposes: storing the output from the process, and deciding when to kill the process. You can also use the buffer to identify a process to operate on, since in normal practice only one process is associated with any given buffer. Many applications of processes also use the buffer for editing input to be sent to the process, but this is not built into Emacs Lisp.
By default, process output is inserted in the associated buffer.
(You can change this by defining a custom filter function,
see Process Filter Functions.) The position to insert the output is
determined by the process-mark, which is then updated to point
to the end of the text just inserted. Usually, but not always, the
process-mark is at the end of the buffer.
Killing the associated buffer of a process also kills the process.
Emacs asks for confirmation first, if the process’s
process-query-on-exit-flag is non-nil (see Querying Before Exit). This confirmation is done by the function
process-kill-buffer-query-function, which is run from
kill-buffer-query-functions (see Killing Buffers).
This function returns the associated buffer of the specified process.
(process-buffer (get-process "shell"))
⇒ #<buffer *shell*>
This function returns the process marker for process, which is the marker that says where to insert output from the process.
If process does not have a buffer, process-mark returns a
marker that points nowhere.
The default filter function uses this marker to decide where to insert process output, and updates it to point after the inserted text. That is why successive batches of output are inserted consecutively.
Custom filter functions normally should use this marker in the same fashion.
For an example of a filter function that uses process-mark,
see Process Filter Example.
When the user is expected to enter input in the process buffer for transmission to the process, the process marker separates the new input from previous output.
This function sets the buffer associated with process to
buffer. If buffer is nil, the process becomes
associated with no buffer; if non-nil and different from the
buffer associated with the process, the process mark will be set to
point to the end of buffer (unless the process mark is already
associated with buffer).
This function returns a nondeleted process associated with the buffer
specified by buffer-or-name. If there are several processes
associated with it, this function chooses one (currently, the one most
recently created, but don’t count on that). Deletion of a process
(see delete-process) makes it ineligible for this function to
return.
It is usually a bad idea to have more than one process associated with the same buffer.
(get-buffer-process "*shell*")
⇒ #<process shell>
Killing the process’s buffer deletes the process, which kills the
subprocess with a SIGHUP signal (see Sending Signals to Processes).
If the process’s buffer is displayed in a window, your Lisp program may wish to tell the process the dimensions of that window, so that the process could adapt its output to those dimensions, much as it adapts to the screen dimensions. The following functions allow communicating this kind of information to processes; however, not all systems support the underlying functionality, so it is best to provide fallbacks, e.g., via command-line arguments or environment variables.
Tell process that its logical window size has dimensions
width by height, in character units. If this function
succeeds in communicating this information to the process, it returns
t; otherwise it returns nil.
When windows that display buffers associated with process change their
dimensions, the affected processes should be told about these changes.
By default, when the window configuration changes, Emacs will
automatically call set-process-window-size on behalf of every
process whose buffer is displayed in a window, passing it the smallest
dimensions of all the windows displaying the process’s buffer. This
works via window-configuration-change-hook (see Hooks for Window Scrolling and Changes), which is told to invoke the function that is the value of
the variable window-adjust-process-window-size-function for
each process whose buffer is displayed in at least one window. You
can customize this behavior by setting the value of that variable.
The value of this variable should be a function of two arguments: a
process and the list of windows displaying the process’s buffer. When
the function is called, the process’s buffer is the current buffer.
The function should return a cons cell (width . height) that describes the dimensions of the logical process
window to be passed via a call to set-process-window-size. The
function can also return nil, in which case Emacs will not call
set-process-window-size for this process.
Emacs supplies two predefined values for this variable:
window-adjust-process-window-size-smallest, which returns the
smallest of all the dimensions of the windows that display a process’s
buffer; and window-adjust-process-window-size-largest, which
returns the largest dimensions. For more complex strategies, write
your own function.
This variable can be buffer-local.
If the process has the adjust-window-size-function property
(see Process Information), its value overrides the global and
buffer-local values of
window-adjust-process-window-size-function.
A process filter function is a function that receives the standard output from the associated process. All output from that process is passed to the filter. The default filter simply outputs directly to the process buffer.
By default, the error output from the process, if any, is also passed to the filter function, unless the destination for the standard error stream of the process was separated from the standard output when the process was created. Emacs will only call the filter function during certain function calls. See Receiving Output from Processes. Note that if any of those functions are called by the filter, the filter may be called recursively.
A filter function must accept two arguments: the associated process and a string, which is output just received from it. The function is then free to do whatever it chooses with the output.
Quitting is normally inhibited within a filter function—otherwise,
the effect of typing C-g at command level or to quit a user
command would be unpredictable. If you want to permit quitting inside
a filter function, bind inhibit-quit to nil. In most
cases, the right way to do this is with the macro
with-local-quit. See Quitting.
If an error happens during execution of a filter function, it is
caught automatically, so that it doesn’t stop the execution of whatever
program was running when the filter function was started. However, if
debug-on-error is non-nil, errors are not caught.
This makes it possible to use the Lisp debugger to debug filter
functions. See The Lisp Debugger. If an error is caught, Emacs pauses for
process-error-pause-time seconds so that the user sees the
error. See Creating an Asynchronous Process.
Many filter functions sometimes (or always) insert the output in the process’s buffer, mimicking the actions of the default filter. Such filter functions need to make sure that they save the current buffer, select the correct buffer (if different) before inserting output, and then restore the original buffer. They should also check whether the buffer is still alive, update the process marker, and in some cases update the value of point. Here is how to do these things:
(defun ordinary-insertion-filter (proc string)
(when (buffer-live-p (process-buffer proc))
(with-current-buffer (process-buffer proc)
(let ((moving (= (point) (process-mark proc))))
(save-excursion
;; Insert the text, advancing the process marker.
(goto-char (process-mark proc))
(insert string)
(set-marker (process-mark proc) (point)))
(if moving (goto-char (process-mark proc)))))))
To make the filter force the process buffer to be visible whenever new
text arrives, you could insert a line like the following just before the
with-current-buffer construct:
(display-buffer (process-buffer proc))
To force point to the end of the new output, no matter where it was
previously, eliminate the variable moving from the example and
call goto-char unconditionally. Note that this doesn’t
necessarily move window point. The default filter actually uses
insert-before-markers which moves all markers, including window
point. This may move unrelated markers, so it’s generally better to
move window point explicitly, or set its insertion type to t
(see Windows and Point).
Note that Emacs automatically saves and restores the match data while executing filter functions. See The Match Data.
The output to the filter may come in chunks of any size. A program that produces the same output twice in a row may send it as one batch of 200 characters one time, and five batches of 40 characters the next. If the filter looks for certain text strings in the subprocess output, make sure to handle the case where one of these strings is split across two or more batches of output; one way to do this is to insert the received text into a temporary buffer, which can then be searched.
This function gives process the filter function filter.
If filter is nil, it gives the process the default
filter, which inserts the process output into the process buffer. If
filter is t, Emacs stops accepting output from the
process, unless it’s a network server process that listens for
incoming connections.
This function returns the filter function of process.
In case the process’s output needs to be passed to several filters, you can
use add-function to combine an existing filter with a new one.
See Advising Emacs Lisp Functions.
Here is an example of the use of a filter function:
(defun keep-output (process output)
(setq kept (cons output kept)))
⇒ keep-output
(setq kept nil)
⇒ nil
(set-process-filter (get-process "shell") 'keep-output)
⇒ keep-output
(process-send-string "shell" "ls ~/other\n")
⇒ nil
kept
⇒ ("lewis@slug:$ "
"FINAL-W87-SHORT.MSS backup.otl kolstad.mss~ address.txt backup.psf kolstad.psf backup.bib~ david.mss resume-Dec-86.mss~ backup.err david.psf resume-Dec.psf backup.mss dland syllabus.mss " "#backups.mss# backup.mss~ kolstad.mss ")
When Emacs writes process output directly into a multibyte buffer,
it decodes the output according to the process output coding system.
If the coding system is raw-text or no-conversion, Emacs
converts the unibyte output to multibyte using
string-to-multibyte, and inserts the resulting multibyte text.
You can use set-process-coding-system to specify which coding
system to use (see Process Information). Otherwise, the coding
system comes from coding-system-for-read, if that is
non-nil; or else from the defaulting mechanism (see Default Coding Systems). If the text output by a process contains null
bytes, Emacs by default uses no-conversion for it; see
inhibit-null-byte-detection, for how to
control this behavior.
Warning: Coding systems such as undecided, which
determine the coding system from the data, do not work entirely
reliably with asynchronous subprocess output. This is because Emacs
has to process asynchronous subprocess output in batches, as it
arrives. Emacs must try to detect the proper coding system from one
batch at a time, and this does not always work. Therefore, if at all
possible, specify a coding system that determines both the character
code conversion and the end of line conversion—that is, one like
latin-1-unix, rather than undecided or latin-1.
When Emacs calls a process filter function, it provides the process
output as a multibyte string or as a unibyte string according to the
process’s filter coding system. Emacs
decodes the output according to the process output coding system,
which usually produces a multibyte string, except for coding systems
such as binary and raw-text.
Output from asynchronous subprocesses normally arrives only while Emacs is waiting for some sort of external event, such as elapsed time or terminal input. Occasionally it is useful in a Lisp program to explicitly permit output to arrive at a specific point, or even to wait until output arrives from a process.
This function allows Emacs to read pending output from processes. The
output is given to the filter functions set up by the processes
(see Process Filter Functions). If process is
non-nil then this function does not return until some output
has been received from process or process has closed the
connection.
The arguments seconds and millisec let you specify timeout
periods. The former specifies a period measured in seconds and the
latter specifies one measured in milliseconds. The two time periods
thus specified are added together, and accept-process-output
returns after that much time, even if there is no
subprocess output.
The argument millisec is obsolete (and should not be used), because seconds can be floating point to specify waiting a fractional number of seconds. If seconds is 0, the function accepts whatever output is pending but does not wait.
If process is a process, and the argument just-this-one is
non-nil, only output from that process is handled, suspending output
from other processes until some output has been received from that
process or the timeout expires. If just-this-one is an integer,
also inhibit running timers. This feature is generally not
recommended, but may be necessary for specific applications, such as
speech synthesis.
The function accept-process-output returns non-nil if it
got output from process, or from any process if process is
nil; this can occur even after a process has exited if the
corresponding connection contains buffered data. The function returns
nil if the timeout expired or the connection was closed before output
arrived.
Note that this function is not guaranteed to return as soon as some
output is available from a subprocess, because the main purpose of the
function is to let Emacs read output from subprocesses, not to wait as
little as possible. In particular, if process is nil, the
function should not be expected to return before the specified timeout
expires. Thus, if a Lisp program needs to minimize the wait for the
subprocess output, it should call this function with a non-nil
value of a specific process.
If a connection from a process contains buffered data,
accept-process-output can return non-nil even after the
process has exited. Therefore, although the following loop:
;; This loop contains a bug. (while (process-live-p process) (accept-process-output process))
will often read all output from process, it has a race condition
and can miss some output if process-live-p returns nil
while the connection still contains data. Better is to write the loop
like this:
(while (accept-process-output process))
If you have passed a non-nil stderr to
make-process, it will have a standard error process.
See Creating an Asynchronous Process. In that case, waiting for process
output from the main process doesn’t wait for output from the standard
error process. To make sure you have received both all of standard
output and all of standard error from a process, use the following
code:
(while (accept-process-output process)) (while (accept-process-output stderr-process))
If you passed a buffer to the stderr argument of
make-process, you still have to wait for the standard error
process, like so:
(let* ((stdout (generate-new-buffer "stdout"))
(stderr (generate-new-buffer "stderr"))
(process (make-process :name "test"
:command '("my-program")
:buffer stdout
:stderr stderr))
(stderr-process (get-buffer-process stderr)))
(unless (and process stderr-process)
(error "Process unexpectedly nil"))
(while (accept-process-output process))
(while (accept-process-output stderr-process)))
Only when both accept-process-output forms return nil,
you can be sure that the process has exited and Emacs has read all its
output.
Reading pending standard error from a process running on a remote host is not possible this way.
Because threads were a relatively late addition to Emacs Lisp, and
due to the way dynamic binding was sometimes used in conjunction with
accept-process-output, by default a process is locked to the
thread that created it. When a process is locked to a thread, output
from the process can only be accepted by that thread.
A Lisp program can specify to which thread a process is to be
locked, or instruct Emacs to unlock a process, in which case its
output can be processed by any thread. Only a single thread will wait
for output from a given process at one time—once one thread begins
waiting for output, the process is temporarily locked until
accept-process-output or sit-for returns.
If the thread exits, all the processes locked to it are unlocked.
Return the thread to which process is locked. If process
is unlocked, return nil.
Set the locking thread of process to thread. thread
may be nil, in which case the process is unlocked.
A process sentinel is a function that is called whenever the associated process changes status for any reason, including signals (whether sent by Emacs or caused by the process’s own actions) that terminate, stop, or continue the process. The process sentinel is also called if the process exits. The sentinel receives two arguments: the process for which the event occurred, and a string describing the type of event.
If no sentinel function was specified for a process, it will use the default sentinel function, which inserts a message in the process’s buffer with the process name and the string describing the event.
The string describing the event looks like one of the following (but this is not an exhaustive list of event strings):
"finished\n".
"deleted\n".
"exited abnormally with code exitcode (core dumped)\n".
The “core dumped” part is optional, and only appears if the process
dumped core.
"failed with code fail-code\n".
"signal-description (core dumped)\n". The
signal-description is a system-dependent textual description of
a signal, e.g., "killed" for SIGKILL. The “core
dumped” part is optional, and only appears if the process dumped
core.
"open from host-name\n".
"open\n".
"run\n".
"connection broken by remote peer\n".
A sentinel runs only while Emacs is waiting (e.g., for terminal
input, or for time to elapse, or for process output). This avoids the
timing errors that could result from running sentinels at random places in
the middle of other Lisp programs. A program can wait, so that
sentinels will run, by calling sit-for or sleep-for
(see Waiting for Elapsed Time or Input), or accept-process-output (see Accepting Output from Processes). Emacs also allows sentinels to run when the command loop is
reading input. delete-process calls the sentinel when it
terminates a running process.
Emacs does not keep a queue of multiple reasons to call the sentinel of one process; it records just the current status and the fact that there has been a change. Therefore two changes in status, coming in quick succession, can call the sentinel just once. However, process termination will always run the sentinel exactly once. This is because the process status can’t change again after termination.
Emacs explicitly checks for output from the process before running the process sentinel. Once the sentinel runs due to process termination, no further output can arrive from the process.
A sentinel that writes the output into the buffer of the process
should check whether the buffer is still alive. If it tries to insert
into a dead buffer, it will get an error. If the buffer is dead,
(buffer-name (process-buffer process)) returns nil.
Quitting is normally inhibited within a sentinel—otherwise, the
effect of typing C-g at command level or to quit a user command
would be unpredictable. If you want to permit quitting inside a
sentinel, bind inhibit-quit to nil. In most cases, the
right way to do this is with the macro with-local-quit.
See Quitting.
If an error happens during execution of a sentinel, it is caught
automatically, so that it doesn’t stop the execution of whatever
programs was running when the sentinel was started. However, if
debug-on-error is non-nil, errors are not caught.
This makes it possible to use the Lisp debugger to debug the
sentinel. See The Lisp Debugger. If an error is caught, Emacs pauses for
process-error-pause-time seconds so that the user sees the
error. See Creating an Asynchronous Process.
While a sentinel is running, the process sentinel is temporarily
set to nil so that the sentinel won’t run recursively.
For this reason it is not possible for a sentinel to specify
a new sentinel.
Note that Emacs automatically saves and restores the match data while executing sentinels. See The Match Data.
This function associates sentinel with process. If
sentinel is nil, then the process will have the default
sentinel, which inserts a message in the process’s buffer when the
process status changes.
Changes in process sentinels take effect immediately—if the sentinel is slated to be run but has not been called yet, and you specify a new sentinel, the eventual call to the sentinel will use the new one.
(defun msg-me (process event)
(princ
(format "Process: %s had the event '%s'" process event)))
(set-process-sentinel (get-process "shell") 'msg-me)
⇒ msg-me
(kill-process (get-process "shell"))
⊣ Process: #<process shell> had the event 'killed'
⇒ #<process shell>
This function returns the sentinel of process.
In case a process status changes need to be passed to several sentinels, you
can use add-function to combine an existing sentinel with a new one.
See Advising Emacs Lisp Functions.
While a sentinel or filter function is running, this function returns
non-nil if Emacs was waiting for keyboard input from the user at
the time the sentinel or filter function was called, or nil if it
was not.
When Emacs exits, it terminates all its subprocesses. For
subprocesses that run a program, it sends them the SIGHUP
signal; connections are simply closed. Because subprocesses may be
doing valuable work, Emacs normally asks the user to confirm that it
is ok to terminate them. Each process has a query flag, which, if
non-nil, says that Emacs should ask for confirmation before
exiting and thus killing that process. The default for the query flag
is t, meaning do query.
This returns the query flag of process.
This function sets the query flag of process to flag. It returns flag.
Here is an example of using set-process-query-on-exit-flag on a
shell process to avoid querying:
(set-process-query-on-exit-flag (get-process "shell") nil)
⇒ nil
If this user option is set to t (the default), then Emacs asks
for confirmation before killing processes on exit. If it is
nil, Emacs kills processes without confirmation, i.e., the
query flag of all processes is ignored.
In addition to accessing and manipulating processes that are subprocesses of the current Emacs session, Emacs Lisp programs can also access other processes. We call these system processes, to distinguish them from Emacs subprocesses.
Emacs provides several primitives for accessing system processes.
Not all platforms support these primitives; on those which don’t,
these primitives return nil.
This function returns a list of all the processes running on the system. Each process is identified by its PID, a numerical process ID that is assigned by the OS and distinguishes the process from all the other processes running on the same machine at the same time.
If default-directory points to a remote host, processes of that
host are returned.
This function returns an alist of attributes for the process specified
by its process ID pid. Each association in the alist is of the
form (key . value), where key designates the
attribute and value is the value of that attribute. The various
attribute keys that this function can return are listed below.
Not all platforms support all of these attributes; if an attribute is
not supported, its association will not appear in the returned alist.
If default-directory points to a remote host, pid is
regarded as process of that host.
euidThe effective user ID of the user who invoked the process. The
corresponding value is a number. If the process was invoked by
the same user who runs the current Emacs session, the value is
identical to what user-uid returns (see User Identification).
userUser name corresponding to the process’s effective user ID, a string.
egidThe group ID of the effective user ID, a number.
groupGroup name corresponding to the effective user’s group ID, a string.
commThe name of the command that runs in the process. This is a string that usually specifies the name of the executable file of the process, without the leading directories. However, some special system processes can report strings that do not correspond to an executable file of a program.
stateThe state code of the process. This is a short string that encodes the scheduling state of the process. Here’s a list of the most frequently seen codes:
"D"uninterruptible sleep (usually I/O)
"R"running
"S"interruptible sleep (waiting for some event)
"T"stopped, e.g., by a job control signal
"Z"zombie: a process that terminated, but was not reaped by its parent
For the full list of the possible states, see the manual page of the
ps command.
ppidThe process ID of the parent process, a number.
pgrpThe process group ID of the process, a number.
sessThe session ID of the process. This is a number that is the process ID of the process’s session leader.
ttnameA string that is the name of the process’s controlling terminal. On Unix and GNU systems, this is normally the file name of the corresponding terminal device, such as /dev/pts65.
tpgidThe numerical process group ID of the foreground process group that uses the process’s terminal.
minfltThe number of minor page faults caused by the process since its beginning. (Minor page faults are those that don’t involve reading from disk.)
majfltThe number of major page faults caused by the process since its beginning. (Major page faults require a disk to be read, and are thus more expensive than minor page faults.)
cminfltcmajfltLike minflt and majflt, but include the number of page
faults for all the child processes of the given process.
utimeTime spent by the process in the user context, for running the application’s code. The corresponding value is a Lisp timestamp (see Time of Day).
stimeTime spent by the process in the system (kernel) context, for processing system calls. The corresponding value is a Lisp timestamp.
timeThe sum of utime and stime. The corresponding
value is a Lisp timestamp.
cutimecstimectimeLike utime, stime, and time, but include the
times of all the child processes of the given process.
priThe numerical priority of the process.
niceThe nice value of the process, a number. (Processes with smaller nice values get scheduled more favorably.)
thcountThe number of threads in the process.
startThe time when the process was started, as a Lisp timestamp.
etimeThe time elapsed since the process started, as a Lisp timestamp.
vsizeThe virtual memory size of the process, measured in kilobytes.
rssThe size of the process’s resident set, the number of kilobytes occupied by the process in the machine’s physical memory.
pcpuThe percentage of the CPU time used by the process since it started. The corresponding value is a nonnegative floating-point number. Although in theory the number can exceed 100 on a multicore platform, it is usually less than 100 because Emacs is typically single-threaded.
pmemThe percentage of the total physical memory installed on the machine used by the process’s resident set. The value is a floating-point number between 0 and 100.
argsThe command-line with which the process was invoked. This is a string
in which individual command-line arguments are separated by blanks;
whitespace characters that are embedded in the arguments are quoted as
appropriate for the system’s shell: escaped by backslash characters on
GNU and Unix, and enclosed in double quote characters on Windows.
Thus, this command-line string can be directly used in primitives such
as shell-command.
You can use a transaction queue to communicate with a subprocess
using transactions. First use tq-create to create a transaction
queue communicating with a specified process. Then you can call
tq-enqueue to send a transaction.
This function creates and returns a transaction queue communicating with process. The argument process should be a subprocess capable of sending and receiving streams of bytes. It may be a child process, or it may be a TCP connection to a server, possibly on another machine.
This function sends a transaction to queue queue. Specifying the queue has the effect of specifying the subprocess to talk to.
The argument question is the outgoing message that starts the transaction. The argument fn is the function to call when the corresponding answer comes back; it is called with two arguments: closure, and the answer received.
The argument regexp is a regular expression that should match
text at the end of the entire answer, but nothing before; that’s how
tq-enqueue determines where the answer ends.
If the argument delay-question is non-nil, delay sending
this question until the process has finished replying to any previous
questions. This produces more reliable results with some processes.
Shut down transaction queue queue, waiting for all pending transactions to complete, and then terminate the connection or child process.
Transaction queues are implemented by means of a filter function. See Process Filter Functions.
Emacs Lisp programs can open stream (TCP) and datagram (UDP) network
connections (see Datagrams) to other processes on the same machine
or other machines.
A network connection is handled by Lisp much like a subprocess, and is
represented by a process object. However, the process you are
communicating with is not a child of the Emacs process, has no
process ID, and you can’t kill it or send it signals. All you
can do is send and receive data. delete-process closes the
connection, but does not kill the program at the other end; that
program must decide what to do about closure of the connection.
Lisp programs can listen for connections by creating network servers. A network server is also represented by a kind of process object, but unlike a network connection, the network server never transfers data itself. When it receives a connection request, it creates a new network connection to represent the connection just made. (The network connection inherits certain information, including the process plist, from the server.) The network server then goes back to listening for more connection requests.
Network connections and servers are created by calling
make-network-process with an argument list consisting of
keyword/argument pairs, for example :server t to create a
server process, or :type 'datagram to create a datagram
connection. See Low-Level Network Access, for details. You can also use
the open-network-stream function described below.
To distinguish the different types of processes, the
process-type function returns the symbol network for a
network connection or server, serial for a serial port
connection, pipe for a pipe connection, or real for a
real subprocess.
The process-status function returns open,
closed, connect, stop, or failed for
network connections. For a network server, the status is always
listen. Except for stop, none of those values is
possible for a real subprocess. See Process Information.
You can stop and resume operation of a network process by calling
stop-process and continue-process. For a server
process, being stopped means not accepting new connections. (Up to 5
connection requests will be queued for when you resume the server; you
can increase this limit, unless it is imposed by the operating
system—see the :server keyword of make-network-process,
make-network-process.) For a network stream connection, being
stopped means not processing input (any arriving input waits until you
resume the connection). For a datagram connection, some number of
packets may be queued but input may be lost. You can use the function
process-command to determine whether a network connection or
server is stopped; a non-nil value means yes.
Emacs can create encrypted network connections, using the built-in
support for the GnuTLS Transport Layer Security Library; see
the GnuTLS project page.
If your Emacs was compiled with GnuTLS support, the function
gnutls-available-p is defined and returns non-nil. For
more details, see Overview in The Emacs-GnuTLS manual.
The open-network-stream function can transparently handle the
details of creating encrypted connections for you, using whatever
support is available.
This function opens a TCP connection, with optional encryption, and returns a process object that represents the connection.
The name argument specifies the name for the process object. It is modified as necessary to make it unique.
The buffer argument is the buffer to associate with the
connection. Output from the connection is inserted in the buffer,
unless you specify your own filter function to handle the output. If
buffer is nil, it means that the connection is not
associated with any buffer.
The arguments host and service specify where to connect to;
host is the host name (a string), and service is the name of
a defined network service (a string) or a port number (an integer like
80 or an integer string like "80").
The remaining arguments parameters are keyword/argument pairs that are mainly relevant to encrypted connections:
:nowait booleanIf non-nil, try to make an asynchronous connection.
:noquery query-flagInitialize the process query flag to query-flag. See Querying Before Exit.
:coding codingUse this to set the coding systems used by the network process, in
preference to binding coding-system-for-read or
coding-system-for-write. See make-network-process, for
details.
:type typeThe type of connection. Options are:
plainAn ordinary, unencrypted connection.
tlssslA TLS (Transport Layer Security) connection.
nilnetworkStart with a plain connection, and if parameters ‘:success’ and ‘:capability-command’ are supplied, try to upgrade to an encrypted connection via STARTTLS. If that fails, retain the unencrypted connection.
starttlsAs for nil, but if STARTTLS fails, drop the connection.
shellA shell connection.
:always-query-capabilities booleanIf non-nil, always ask for the server’s capabilities, even when
doing a ‘plain’ connection.
:capability-command capability-commandCommand to query the host capabilities. This can either be a string (which will then be sent verbatim to the server) or a function (called with a single parameter: the “greeting” from the server when connecting) that should return a string.
:end-of-command regexp:end-of-capability regexpRegular expression matching the end of a command, or the end of the command capability-command. The latter defaults to the former.
:starttls-function functionFunction of one argument (the response to capability-command),
which returns either nil or the command to activate
STARTTLS, if supported.
:success regexpRegular expression matching a successful STARTTLS negotiation.
:use-starttls-if-possible booleanIf non-nil, do opportunistic STARTTLS upgrades even if Emacs
doesn’t have built-in TLS support.
:warn-unless-encrypted booleanIf non-nil, warn the user if the final connection type is not
encrypted. This is useful for protocols like IMAP and the
like, where most users would expect the network traffic to be encrypted.
This may be due to STARTTLS upgrade failure, specifying
:return-list non-nil allows you to capture any error
encountered.
:client-certificate list-or-t ¶Either a list of the form (key-file cert-file),
naming the certificate key file and certificate file itself, or
t, meaning to query auth-source for this information
(see auth-source in Emacs auth-source
Library). Only used for TLS or STARTTLS. To
enable automatic queries of auth-source when
:client-certificate is not specified customize
network-stream-use-client-certificates to t.
:return-list cons-or-nilThe return value of this function. If omitted or nil, return a
process object. Otherwise, a cons of the form
(process-object . plist), where plist can
include the following keywords:
:greeting string-or-nilIf non-nil, the greeting string returned by the host.
:capabilities string-or-nilIf non-nil, the host’s capability string.
:type symbolThe connection type: ‘plain’ or ‘tls’.
:error symbolA string describing any error encountered when performing STARTTLS upgrade.
:shell-command string-or-nilIf the connection type is shell, this parameter will be
interpreted as a format-spec string (see Custom Format Strings)
that will be executed to make the connection. The specs available are
‘%s’ for the host name and ‘%p’ for the port number. For
instance, if you want to first ssh to ‘gateway’ before making a
plain connection, then this parameter’s value could be something like
‘ssh gateway nc %s %p’.
You create a server by calling make-network-process
(see make-network-process) with :server t. The server will
listen for connection requests from clients. When it accepts a client
connection request, that creates a new network connection, itself a
process object, with the following parameters:
The server’s process buffer value is never used directly, but the log function can retrieve it and use it to log connections by inserting text there.
process-contact
keywords :host, :service, :remote.
A datagram connection communicates with individual packets rather
than streams of data. Each call to process-send sends one
datagram packet (see Sending Input to Processes), and each datagram
received results in one call to the filter function.
The datagram connection doesn’t have to talk with the same remote
peer all the time. It has a remote peer address which specifies
where to send datagrams to. Each time an incoming datagram is passed
to the filter function, the peer address is set to the address that
datagram came from; that way, if the filter function sends a datagram,
it will go back to that place. You can specify the remote peer
address when you create the datagram connection using the
:remote keyword. You can change it later on by calling
set-process-datagram-address.
If process is a datagram connection or server, this function returns its remote peer address.
If process is a datagram connection or server, this function sets its remote peer address to address.
You can also create network connections by operating at a lower
level than that of open-network-stream, using
make-network-process.
make-network-process ¶The basic function for creating network connections and network
servers is make-network-process. It can do either of those
jobs, depending on the arguments you give it.
This function creates a network connection or server and returns the
process object that represents it. The arguments args are a
list of keyword/argument pairs. Omitting a keyword is always
equivalent to specifying it with value nil, except for
:coding, :filter-multibyte, and :reuseaddr. Here
are the meaningful keywords (those corresponding to network options
are listed in the following section):
:name nameUse the string name as the process name. It is modified if necessary to make it unique.
:type typeSpecify the communication type. A value of nil specifies a
stream connection (the default); datagram specifies a datagram
connection; seqpacket specifies a sequenced packet stream
connection. Both connections and servers can be of these types.
:server server-flagIf server-flag is non-nil, create a server. Otherwise,
create a connection. For a stream type server, server-flag may
be an integer, which then specifies the length of the queue of pending
connections to the server. The default queue length is 5.
:host hostSpecify the host to connect to. host should be a host name or
Internet address, as a string, or the symbol local to specify
the local host. If you specify host for a server, it must
specify a valid address for the local host, and only clients
connecting to that address will be accepted. When using local,
by default IPv4 will be used, specify a family of ipv6 to
override this. To listen on all interfaces, specify an address of
‘"0.0.0.0"’ for IPv4 or ‘"::"’ for IPv6. Note that on some
operating systems, listening on ‘"::"’ will also listen on IPv4,
so attempting to then listen separately on IPv4 will result in
EADDRINUSE errors (‘"Address already in use"’).
:service serviceservice specifies a port number to connect to; or, for a server,
the port number to listen on. It should be a service name like
‘"https"’ that translates to a port number, or an integer like ‘443’
or an integer string like ‘"443"’ that specifies the port number
directly. For a server, it can also be t, which means to let
the system select an unused port number.
:family familyfamily specifies the address (and protocol) family for
communication. nil means determine the proper address family
automatically for the given host and service.
local specifies a Unix socket, in which case host is
ignored. ipv4 and ipv6 specify to use IPv4 and IPv6,
respectively.
:use-external-socket use-external-socketIf use-external-socket is non-nil use any sockets passed
to Emacs on invocation instead of allocating one. This is used by the
Emacs server code to allow on-demand socket activation. If Emacs
wasn’t passed a socket, this option is silently ignored.
:local local-addressFor a server process, local-address is the address to listen on. It overrides family, host and service, so you might as well not specify them.
:remote remote-addressFor a connection, remote-address is the address to connect to. It overrides family, host and service, so you might as well not specify them.
For a datagram server, remote-address specifies the initial setting of the remote datagram address.
The format of local-address or remote-address depends on the address family:
[a b c d p] corresponding to
numeric IPv4 address a.b.c.d and port number
p.
[a b c d e f
g h p] corresponding to numeric IPv6 address
a:b:c:d:e:f:g:h and
port number p.
(f . av), where f is the family number and
av is a vector specifying the socket address using one element
per address data byte. Do not rely on this format in portable code,
as it may depend on implementation defined constants, data sizes, and
data structure alignment.
:nowait boolIf bool is non-nil for a stream connection, return
without waiting for the connection to complete. When the connection
succeeds or fails, Emacs will call the sentinel function, with a
second argument matching "open" (if successful) or
"failed". The default is to block, so that
make-network-process does not return until the connection has
succeeded or failed.
If you’re setting up an asynchronous TLS connection, you have to also
provide the :tls-parameters parameter (see below).
Depending on the capabilities of Emacs, how asynchronous
:nowait is may vary. The three elements that may (or may not)
be done asynchronously are domain name resolution, socket setup, and
(for TLS connections) TLS negotiation.
Many functions that interact with process objects, (for instance,
process-datagram-address) rely on them at least having a socket
before they can return a useful value. These functions will block
until the socket has achieved the desired status. The recommended way
of interacting with asynchronous sockets is to place a sentinel on the
process, and not try to interact with it before it has changed status
to ‘"run"’. That way, none of these functions will block.
:tls-parametersWhen opening a TLS connection, this should be where the first element
is the TLS type (which should either be gnutls-x509pki or
gnutls-anon, and the remaining elements should form a keyword
list acceptable for gnutls-boot. (This keyword list can be
obtained from the gnutls-boot-parameters function.) The TLS
connection will then be negotiated after completing the connection to
the host.
:stop stoppedIf stopped is non-nil, start the network connection or
server in the stopped state.
:buffer bufferUse buffer as the process buffer.
:coding codingUse coding as the coding system for this process. To specify
different coding systems for decoding data from the connection and for
encoding data sent to it, specify (decoding .
encoding) for coding.
If you don’t specify this keyword at all, the default is to determine the coding systems from the data.
:noquery query-flagInitialize the process query flag to query-flag. See Querying Before Exit.
:filter filterInitialize the process filter to filter.
:filter-multibyte multibyteIf multibyte is non-nil, strings given to the process
filter are multibyte, otherwise they are unibyte. The default is t.
:sentinel sentinelInitialize the process sentinel to sentinel.
:log logInitialize the log function of a server process to log. The log function is called each time the server accepts a network connection from a client. The arguments passed to the log function are server, connection, and message; where server is the server process, connection is the new process for the connection, and message is a string describing what has happened.
:plist plistInitialize the process plist to plist.
The original argument list, modified with the actual connection
information, is available via the process-contact function.
The following network options can be specified when you create a
network process. Except for :reuseaddr, you can also set or
modify these options later, using set-network-process-option.
For a server process, the options specified with
make-network-process are not inherited by the client
connections, so you will need to set the necessary options for each
child connection as it is created.
:bindtodevice device-nameIf device-name is a non-empty string identifying a network
interface name (see network-interface-list), only handle
packets received on that interface. If device-name is nil
(the default), handle packets received on any interface.
Using this option may require special privileges on some systems.
:broadcast broadcast-flagIf broadcast-flag is non-nil for a datagram process, the
process will receive datagram packet sent to a broadcast address, and
be able to send packets to a broadcast address. This is ignored for a stream
connection.
:dontroute dontroute-flagIf dontroute-flag is non-nil, the process can only send
to hosts on the same network as the local host.
:keepalive keepalive-flagIf keepalive-flag is non-nil for a stream connection,
enable exchange of low-level keep-alive messages.
:linger linger-argIf linger-arg is non-nil, wait for successful
transmission of all queued packets on the connection before it is
deleted (see delete-process). If linger-arg is an
integer, it specifies the maximum time in seconds to wait for queued
packets to be sent before closing the connection. The default is
nil, which means to discard unsent queued packets when the
process is deleted.
:oobinline oobinline-flagIf oobinline-flag is non-nil for a stream connection,
receive out-of-band data in the normal data stream. Otherwise, ignore
out-of-band data.
:priority prioritySet the priority for packets sent on this connection to the integer priority. The interpretation of this number is protocol specific; such as setting the TOS (type of service) field on IP packets sent on this connection. It may also have system dependent effects, such as selecting a specific output queue on the network interface.
:reuseaddr reuseaddr-flagIf reuseaddr-flag is non-nil (the default) for a stream
server process, allow this server to reuse a specific port number (see
:service), unless another process on this host is already
listening on that port. If reuseaddr-flag is nil, there
may be a period of time after the last use of that port (by any
process on the host) where it is not possible to make a new server on
that port.
:nodelay nodelay-flagIf nodelay-flag is non-nil, the TCP_NODELAY option
is enabled on the socket. This disables the Nagle algorithm, meaning
that network segments are sent as soon as possible, even when they
contain little data. This reduces network latency on the network
connection, but can lead to many small packets being sent.
This function sets or modifies a network option for network process
process. The accepted options and values are as for
make-network-process. If no-error is non-nil,
this function returns nil instead of signaling an error if
option is not a supported option. If the function successfully
completes, it returns t.
The current setting of an option is available via the
process-contact function.
To test for the availability of a given network feature, use
featurep like this:
(featurep 'make-network-process '(keyword value))
The result of this form is t if it works to specify
keyword with value value in make-network-process.
Here are some of the keyword—value pairs you can test in
this way.
(:nowait t)Non-nil if non-blocking connect is supported.
(:type datagram)Non-nil if datagrams are supported.
(:family local)Non-nil if local (a.k.a. “UNIX domain”) sockets are supported.
(:family ipv6)Non-nil if IPv6 is supported.
(:service t)Non-nil if the system can select the port for a server.
To test for the availability of a given network option, use
featurep like this:
(featurep 'make-network-process 'keyword)
The accepted keyword values are :bindtodevice, etc.
For the complete list, see Network Options. This form returns
non-nil if that particular network option is supported by
make-network-process (or set-network-process-option).
These additional functions are useful for creating and operating on network connections. Note that they are supported only on some systems.
This function returns a list describing the network interfaces of the
machine you are using. The value is an alist whose elements have the
form (ifname . address). ifname is a string
naming the interface, address has the same form as the
local-address and remote-address arguments to
make-network-process, i.e. a vector of integers. By default
both IPv4 and IPv6 addresses are returned if possible.
Optional argument full non-nil means to instead return a
list of one or more elements of the form (ifname addr bcast netmask). ifname is a non-unique
string naming the interface. addr, bcast, and
netmask are vectors of integers detailing the IP address,
broadcast address, and network mask.
Optional argument family specified as symbol ipv4 or
ipv6 restricts the returned information to IPv4 and IPv6
addresses respectively, independently of the value of full.
Specifying ipv6 when IPv6 support is not available will result
in an error being signaled.
Some examples:
(network-interface-list) ⇒
(("vmnet8" .
[172 16 76 1 0])
("vmnet1" .
[172 16 206 1 0])
("lo0" .
[65152 0 0 0 0 0 0 1 0])
("lo0" .
[0 0 0 0 0 0 0 1 0])
("lo0" .
[127 0 0 1 0]))
(network-interface-list t) ⇒
(("vmnet8"
[172 16 76 1 0]
[172 16 76 255 0]
[255 255 255 0 0])
("vmnet1"
[172 16 206 1 0]
[172 16 206 255 0]
[255 255 255 0 0])
("lo0"
[65152 0 0 0 0 0 0 1 0]
[65152 0 0 0 65535 65535 65535 65535 0]
[65535 65535 65535 65535 0 0 0 0 0])
("lo0"
[0 0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1 0]
[65535 65535 65535 65535 65535 65535 65535 65535 0])
("lo0"
[127 0 0 1 0]
[127 255 255 255 0]
[255 0 0 0 0]))
This function returns information about the network interface named
ifname. The value is a list of the form
(addr bcast netmask hwaddr flags).
The Internet protocol address.
The broadcast address.
The network mask.
The layer 2 address (Ethernet MAC address, for instance).
The current flags of the interface.
Note that this function returns only IPv4 information.
This function converts the Lisp representation of a network address to a string.
A five-element vector [a b c d p]
represents an IPv4 address a.b.c.d and port
number p. format-network-address converts that to the
string "a.b.c.d:p".
A nine-element vector [a b c d e
f g h p] represents an IPv6 address along
with a port number. format-network-address converts that to
the string
"[a:b:c:d:e:f:g:h]:p".
If the vector does not include the port number, p, or if
omit-port is non-nil, the result does not include the
:p suffix.
This function perform hostname lookups on name, which is
expected to be an ASCII-only string, otherwise it signals an error. Call
puny-encode-domain on name first if you wish to lookup
internationalized hostnames.
If successful, this function returns a list of Lisp representations of network
addresses (see make-network-process, for a description of the
format), otherwise return nil. In the latter case, it also logs
an error message hopefully explaining what went wrong.
By default, this function attempts both IPv4 and IPv6 lookups. The
optional argument family controls this behavior, specifying the
symbol ipv4 or ipv6 restricts lookups to IPv4 and IPv6
respectively.
If optional argument hints is numeric, the function
treats the name as a numerical IP address (and does not perform DNS
lookups). This can be used to check whether a string is a valid
numerical representation of an IP address, or to convert a numerical
string to its canonical representation. e.g.
(network-lookup-address-info "127.1" 'ipv4 'numeric)
⇒ ([127 0 0 1 0])
(network-lookup-address-info "::1" nil 'numeric)
⇒ ([0 0 0 0 0 0 0 1 0])
Be warned that there are some surprising valid forms, especially for IPv4, e.g ‘0xe3010203’ and ‘0343.1.2.3’ are both valid, as are ‘0’ and ‘1’ (but they are invalid for IPv6).
Emacs can communicate with serial ports. For interactive use,
M-x serial-term opens a terminal window. In a Lisp program,
make-serial-process creates a process object.
The serial port can be configured at run-time, without having to
close and re-open it. The function serial-process-configure
lets you change the speed, bytesize, and other parameters. In a
terminal window created by serial-term, you can click on the
mode line for configuration.
A serial connection is represented by a process object, which can be
used in a similar way to a subprocess or network process. You can send and
receive data, and configure the serial port. A serial process object
has no process ID, however, and you can’t send signals to it, and the
status codes are different from other types of processes.
delete-process on the process object or kill-buffer on
the process buffer close the connection, but this does not affect the
device connected to the serial port.
The function process-type returns the symbol serial
for a process object representing a serial port connection.
Serial ports are available on GNU/Linux, Unix, and MS Windows systems.
Start a terminal-emulator for a serial port in a new buffer. port is the name of the serial port to connect to. For example, this could be /dev/ttyS0 on Unix. On MS Windows, this could be COM1, or \\.\COM10 (double the backslashes in Lisp strings).
speed is the speed of the serial port in bits per second. 9600
is a common value. The buffer is in Term mode; see Term Mode in The GNU Emacs Manual, for the commands to use in that buffer.
You can change the speed and the configuration in the mode line menu.
If line-mode is non-nil, term-line-mode is used;
otherwise term-raw-mode is used.
This function creates a process and a buffer. Arguments are specified as keyword/argument pairs. Here’s the list of the meaningful keywords, with the first two (port and speed) being mandatory:
:port portThis is the name of the serial port. On Unix and GNU systems, this is a file name such as /dev/ttyS0. On Windows, this could be COM1, or \\.\COM10 for ports higher than COM9 (double the backslashes in Lisp strings).
:speed speedThe speed of the serial port in bits per second. This function calls
serial-process-configure to handle the speed; see the
following documentation of that function for more details.
:name nameThe name of the process. If name is not given, port will serve as the process name as well.
:buffer bufferThe buffer to associate with the process. The value can be either a
buffer or a string that names a buffer. Process output goes at the
end of that buffer, unless you specify an output stream or filter
function to handle the output. If buffer is not given, the
process buffer’s name is taken from the value of the :name
keyword.
:coding codingIf coding is a symbol, it specifies the coding system used for
both reading and writing for this process. If coding is a cons
(decoding . encoding), decoding is used for
reading, and encoding is used for writing. If not specified,
the default is to determine the coding systems from the data itself.
:noquery query-flagInitialize the process query flag to query-flag. See Querying Before Exit. The flags defaults to nil if unspecified.
:stop boolStart process in the stopped state if bool is
non-nil. In the stopped state, a serial process does not
accept incoming data, but you can send outgoing data. The stopped
state is cleared by continue-process and set by
stop-process.
:filter filterInstall filter as the process filter.
:sentinel sentinelInstall sentinel as the process sentinel.
:plist plistInstall plist as the initial plist of the process.
:bytesize:parity:stopbits:flowcontrolThese are handled by serial-process-configure, which is called
by make-serial-process.
The original argument list, possibly modified by later configuration,
is available via the function process-contact.
Here is an example:
(make-serial-process :port "/dev/ttyS0" :speed 9600)
This function configures a serial port connection. Arguments are
specified as keyword/argument pairs. Attributes that are not given
are re-initialized from the process’s current configuration (available
via the function process-contact), or set to reasonable default
values. The following arguments are defined:
:process process:name name:buffer buffer:port portAny of these arguments can be given to identify the process that is to be configured. If none of these arguments is given, the current buffer’s process is used.
:speed speedThe speed of the serial port in bits per second, a.k.a. baud
rate. The value can be any number, but most serial ports work only
at a few defined values between 1200 and 115200, with 9600 being the
most common value. If speed is nil, the function ignores
all other arguments and does not configure the port. This may be
useful for special serial ports such as Bluetooth-to-serial converters,
which can only be configured through ‘AT’ commands sent through the
connection. The value of nil for speed is valid only for
connections that were already opened by a previous call to
make-serial-process or serial-term.
:bytesize bytesizeThe number of bits per byte, which can be 7 or 8. If bytesize
is not given or nil, it defaults to 8.
:parity parityThe value can be nil (don’t use parity), the symbol
odd (use odd parity), or the symbol even (use even
parity). If parity is not given, it defaults to no parity.
:stopbits stopbitsThe number of stopbits used to terminate a transmission
of each byte. stopbits can be 1 or 2. If stopbits is not
given or nil, it defaults to 1.
:flowcontrol flowcontrolThe type of flow control to use for this connection, which is either
nil (don’t use flow control), the symbol hw (use RTS/CTS
hardware flow control), or the symbol sw (use XON/XOFF software
flow control). If flowcontrol is not given, it defaults to no
flow control.
Internally, make-serial-process calls
serial-process-configure for the initial configuration of the
serial port.
This section describes how to pack and unpack arrays of bytes,
usually for binary network protocols. These functions convert byte arrays
to alists, and vice versa. The byte array can be represented as a
unibyte string or as a vector of integers, while the alist associates
symbols either with fixed-size objects or with recursive sub-alists.
To use the functions referred to in this section, load the
bindat library.
Conversion from byte arrays to nested alists is also known as deserializing or unpacking, while going in the opposite direction is also known as serializing or packing.
To control unpacking and packing, you write a data layout
specification, also called a Bindat type expression. This can
be a base type or a composite type made of several fields,
where the specification controls the length of each field to be
processed, and how to pack or unpack it. We normally keep bindat type
values in variables whose names end in -bindat-spec; that kind
of name is automatically recognized as risky (see File Local Variables).
Creates a Bindat type value object according to the Bindat type expression type.
A field’s type describes the size (in bytes) of the object
that the field represents and, in the case of multibyte fields, how
the bytes are ordered within the field. The two possible orderings
are big endian (also known as “network byte ordering”) and
little endian. For instance, the number #x23cd (decimal
9165) in big endian would be the two bytes #x23 #xcd;
and in little endian, #xcd #x23. Here are the possible
type values:
u8byteUnsigned byte, with length 1.
uint bitlen &optional leUnsigned integer in network byte order (big-endian), with bitlen bits.
bitlen has to be a multiple of 8.
If le is non-nil, then use little-endian byte order.
sint bitlen leSigned integer in network byte order (big-endian), with bitlen bits.
bitlen has to be a multiple of 8.
If le is non-nil, then use little-endian byte order.
str lenUnibyte string (see Text Representations) of length len bytes.
When packing, the first len bytes of the input string are copied
to the packed output. If the input string is shorter than len,
the remaining bytes will be null (zero) unless a pre-allocated string
was provided to bindat-pack, in which case the remaining bytes
are left unmodified. If the input string is multibyte with only ASCII
and eight-bit characters, it is converted to unibyte before it
is packed; other multibyte strings signal an error. When unpacking,
any null bytes in the packed input string will appear in the unpacked
output.
strz &optional lenIf len is not provided, this is a variable-length
null-terminated unibyte string (see Text Representations). When
packing into strz, the entire input string is copied to the
packed output followed by a null (zero) byte. (If pre-allocated
string is provided for packing into strz, that pre-allocated
string should have enough space for the additional null byte appended
to the output string contents, see Functions to Unpack and Pack Bytes). The length
of the packed output is the length of the input string plus one (for
the null terminator). The input string must not contain any null
bytes. If the input string is multibyte with only ASCII and
eight-bit characters, it is converted to unibyte before it is
packed; other multibyte strings signal an error. When unpacking a
strz, the resulting output string will contain all bytes up to
(but excluding) the null byte that terminated the input string.
If len is provided, strz behaves the same as str,
but with a couple of differences:
Caution: The packed output will not be null-terminated unless the input string is shorter than len bytes or it contains a null byte within the first len bytes.
vec len [type]Vector of len elements. The type of the elements is given by type, defaulting to bytes. The type can be any Bindat type expression.
repeat len [type]Like vec, but it unpacks to and packs from lists, whereas
vec unpacks to vectors.
bits lenList of bits that are set to 1 in len bytes. The bytes are
taken in big-endian order, and the bits are numbered starting with
8 * len − 1 and ending with zero. For example:
bits 2 unpacks #x28 #x1c to (2 3 4 11 13)
and #x1c #x28 to (3 5 10 11 12).
fill lenlen bytes used as a mere filler. In packing, these bytes are
left unchanged, which normally means they remain zero.
When unpacking, this just returns nil.
align lenSame as fill except the number of bytes is that needed to skip
to the next multiple of len bytes.
type expThis lets you refer to a type indirectly: exp is a Lisp expression which should return a Bindat type value.
unit expThis is a trivial type which uses up 0 bits of space. exp describes the value returned when we try to “unpack” such a field.
struct fields...Composite type made of several fields. Every field is of the form
(name type) where type can be any Bindat
type expression. name can be _ when the field’s value
does not deserve to be named, as is often the case for align
and fill fields.
When the context makes it clear that this is a Bindat type expression,
the symbol struct can be omitted.
In the types above, len and bitlen are given as an integer specifying the number of bytes (or bits) in the field. When the length of a field is not fixed, it typically depends on the value of preceding fields. For this reason, the length len does not have to be a constant but can be any Lisp expression and it can refer to the value of previous fields via their name.
For example, the specification of a data layout where a leading byte gives the size of a subsequent vector of 16 bit integers could be:
(bindat-type (len u8) (payload vec (1+ len) uint 16))
In the following documentation, type refers to a Bindat type
value as returned from bindat-type, raw to a byte
array, and struct to an alist representing unpacked field data.
This function unpacks data from the unibyte string or byte
array raw
according to type. Normally, this starts unpacking at the
beginning of the byte array, but if idx is non-nil, it
specifies a zero-based starting position to use instead.
The value is an alist or nested alist in which each element describes one unpacked field.
This function selects a field’s data from the nested alist
struct. Usually struct was returned by
bindat-unpack. If name corresponds to just one argument,
that means to extract a top-level field value. Multiple name
arguments specify repeated lookup of sub-structures. An integer
name acts as an array index.
For example, (bindat-get-field struct a b 2 c) means
to find field c in the third element of subfield b of
field a. (This corresponds to struct.a.b[2].c in
the C programming language syntax.)
Although packing and unpacking operations change the organization of data (in memory), they preserve the data’s total length, which is the sum of all the fields’ lengths, in bytes. This value is not generally inherent in either the specification or alist alone; instead, both pieces of information contribute to its calculation. Likewise, the length of a string or array being unpacked may be longer than the data’s total length as described by the specification.
This function returns the total length of the data in struct, according to type.
This function returns a byte array packed according to type from
the data in the alist struct. It normally creates and fills a
new byte array starting at the beginning. However, if raw
is non-nil, it specifies a pre-allocated unibyte string or vector to
pack into. If idx is non-nil, it specifies the starting
offset for packing into raw.
When pre-allocating, you should make sure (length raw)
meets or exceeds the total length to avoid an out-of-range error.
Convert the Internet address vector ip to a string in the usual dotted notation.
(bindat-ip-to-string [127 0 0 1])
⇒ "127.0.0.1"
Bindat type expressions are not limited to the types described earlier. They can also be arbitrary Lisp forms returning Bindat type expressions. For example, the type below describes data which can either contain a 24-bit error code or a vector of bytes:
(bindat-type (len u8) (payload . (if (zerop len) (uint 24) (vec (1- len)))))
Furthermore, while composite types are normally unpacked to (and packed from) association lists, this can be changed via the use of the following special keyword arguments:
:unpack-val expWhen the list of fields ends with this keyword argument, then the value returned when unpacking is the value of exp instead of the standard alist. exp can refer to all the previous fields by their name.
:pack-val expIf a field’s type is followed by this keyword argument, then the value packed into this field is returned by exp instead of being extracted from the alist.
:pack-var nameIf the list of fields is preceded by this keyword argument, then all
the subsequent :pack-val arguments can refer to the overall
value to pack into this composite type via the variable named
name.
For example, one could describe a 16-bit signed integer as follows:
(defconst sint16-bindat-spec
(let* ((max (ash 1 15))
(wrap (+ max max)))
(bindat-type :pack-var v
(n uint 16 :pack-val (if (< v 0) (+ v wrap) v))
:unpack-val (if (>= n max) (- n wrap) n))))
Which would then behave as follows:
(bindat-pack sint16-bindat-spec -8)
⇒ "\377\370"
(bindat-unpack sint16-bindat-spec "\300\100")
⇒ -16320
Finally, you can define new Bindat type forms to use in Bindat type
expressions with bindat-defmacro:
Define a new Bindat type expression named name and taking
arguments args. Its behavior follows that of defmacro,
which the important difference that the new forms can only be used
within Bindat type expressions.