"Fossies" - the Fresh Open Source Software Archive

Member "emacs-26.1/doc/lispref/processes.texi" (23 Apr 2018, 141866 Bytes) of package /linux/misc/emacs-26.1.tar.xz:


Caution: As a special service "Fossies" has tried to format the requested Texinfo source page into HTML format but that may be not always succeeeded perfectly. Alternatively you can here view or download the uninterpreted Texinfo source code. A member file download can also be achieved by clicking within a package contents listing on the according byte size field. See also the latest Fossies "Diffs" side-by-side code changes report for "processes.texi": 25.3_vs_26.1.

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1 Processes

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.

Function: processp 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 section Accessing Other Processes.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 Functions that Create Subprocesses

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 section 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 section 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 (@pxref{File Name Expansion}). nil in this list refers to default-directory.

Executing a program can also try adding suffixes to the specified name:

User Option: exec-suffixes

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.

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 section Process Filter Functions, and @ref{Read and Print}.) 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 to specify 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. @xref{System Environment}. The subprocess gets its current directory from the value of default-directory.

Variable: exec-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.

User Option: exec-path

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). @xref{Locating Files, 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.2 Shell Arguments

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:

Function: shell-quote-argument 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. @xref{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))

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.

Function: split-string-and-unquote string &optional separators

This function splits string into substrings at matches for the regular expression separators, like split-string does (@pxref{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 (@pxref{Syntax Class Table}).

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.

Function: combine-and-quote-strings list-of-strings &optional separator

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.3 Creating a Synchronous Process

After a synchronous process is created, Emacs waits for the process to terminate before continuing. Starting Dired on GNU or Unix(1) 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). @xref{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. @xref{Coding Systems}.

Function: call-process program &optional infile destination display &rest args

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:

a buffer

Insert the output in that buffer, before point. This includes both the standard output stream and the standard error stream of the process.

a buffer name (a string)

Insert the output in a buffer with that name, before point.

t

Insert the output in the current buffer, before point.

nil

Discard the output.

0

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))
Function: process-file program &optional infile buffer display &rest args

This function processes files synchronously in a separate process. It is similar to call-process, but may invoke a file 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 handlers may not support all combinations and forms of the arguments infile, buffer, and display. For example, some file handlers might behave as if display were nil, regardless of the value actually passed. As another example, some file handlers might not support separating standard output and error output by way of the buffer argument.

If a file 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 handler. The file 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.

Variable: process-file-side-effects

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 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.

Function: call-process-region start end program &optional delete destination display &rest args

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
Function: call-process-shell-command command &optional infile destination display

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.

Function: process-file-shell-command command &optional infile destination display

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.

Function: call-shell-region start end command &optional delete destination

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.

Function: shell-command-to-string command

This function executes command (a string) as a shell command, then returns the command’s output as a string.

Function: process-lines program &rest args

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.4 Creating an Asynchronous Process

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 section Sending Input to Processes, and see section Receiving Output from Processes). Note that process communication is only partially asynchronous: Emacs sends data to the process only when certain functions are called, and Emacs accepts data from the process only while waiting for input or for a time delay.

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, it is often better to use a pipe, because pipes are more efficient, and because they are immune to stray character injections that ptys introduce for large (around 500 byte) messages. Also, the total number of ptys is limited on many systems and it is good not to waste them.

Function: make-process &rest args

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 allows 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 name

Use 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 buffer

Use buffer as the process buffer. If the value is nil, the subprocess is not associated with any buffer.

:command command

Use 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 coding

If 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; @pxref{Encoding and I/O, file-name-coding-system}).

If coding is nil, the default rules for finding the coding system will apply. @xref{Default Coding Systems}.

:connection-type type

Initialize 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. This parameter and the value of process-connection-type are ignored if a non-nil value is specified for the :stderr parameter; in that case, the type will always be pipe.

:noquery query-flag

Initialize the process query flag to query-flag. See section Querying Before Exit.

:stop stopped

If stopped is non-nil, start the process in the stopped state.

:filter filter

Initialize the process filter to filter. If not specified, a default filter will be provided, which can be overridden later. See section Process Filter Functions.

:sentinel sentinel

Initialize the process sentinel to sentinel. If not specified, a default sentinel will be used, which can be overridden later. See section Sentinels: Detecting Process Status Changes.

:stderr stderr

Associate 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.

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 use start-file-process.

Function: make-pipe-process &rest args

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 name

Use the string name as the process name. As with make-process, it is modified if necessary to make it unique.

:buffer buffer

Use buffer as the process buffer.

:coding coding

If 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. @xref{Default Coding Systems}.

:noquery query-flag

Initialize the process query flag to query-flag. See section Querying Before Exit.

:stop stopped

If 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 section Sending Signals to Processes).

:filter filter

Initialize the process filter to filter. If not specified, a default filter will be provided, which can be changed later. See section Process Filter Functions.

:sentinel sentinel

Initialize the process sentinel to sentinel. If not specified, a default sentinel will be used, which can be changed later. See section Sentinels: Detecting Process Status Changes.

The original argument list, modified with the actual connection information, is available via the process-contact function.

Function: start-process name buffer-or-name program &rest args

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 ----------
Function: start-file-process name buffer-or-name program &rest args

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 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.

Depending on the implementation of the file handler, it might not be possible to apply process-filter or process-sentinel to the resulting process object. See section Process Filter Functions, and Sentinels: Detecting Process Status Changes.

Some file 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.

Function: start-process-shell-command name buffer-or-name command

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 section Shell Arguments. Of course, when executing commands based on user input you should also consider the security implications.

Function: start-file-process-shell-command name buffer-or-name command

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.

Variable: process-connection-type

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.

(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 section Process Information).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.5 Deleting Processes

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 section 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.

User Option: delete-exited-processes

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.

Function: delete-process process

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.) 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 section process-status.

(delete-process "*shell*")
     ⇒ nil

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.6 Process Information

Several functions return information about processes.

Command: list-processes &optional query-only buffer

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 section Querying Before Exit.

Function: process-list

This function returns a list of all processes that have not been deleted.

(process-list)
     ⇒ (#<process display-time> #<process shell>)
Function: get-process name

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>
Function: process-command process

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")
Function: process-contact process &optional key

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):

:buffer

The associated value is the process buffer.

:filter

The associated value is the process filter function. See section Process Filter Functions.

:sentinel

The associated value is the process sentinel function. See section Sentinels: Detecting Process Status Changes.

:remote

In a connection, the address in internal format of the remote peer.

:local

The local address, in internal format.

:service

In 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.

Function: process-id process

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.

Function: process-name process

This function returns the name of process, as a string.

Function: process-status process-name

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:

run

for a process that is running.

stop

for a process that is stopped but continuable.

exit

for a process that has exited.

signal

for a process that has received a fatal signal.

open

for a network, serial, or pipe connection that is open.

closed

for 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.

connect

for a non-blocking connection that is waiting to complete.

failed

for a non-blocking connection that has failed to complete.

listen

for a network server that is listening.

nil

if 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.

Function: process-live-p process

This function returns non-nil if process is alive. A process is considered alive if its status is run, open, listen, connect or stop.

Function: process-type process

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.

Function: process-exit-status process

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.

Function: process-tty-name process

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). If process represents a program running on a remote host, the terminal name used by that program on the remote host is provided as process property remote-tty. If process represents a network, serial, or pipe connection, the value is nil.

Function: process-coding-system process

This function returns a cons cell (decode . encode), describing the coding systems in use for decoding output from, and encoding input to, process (@pxref{Coding Systems}).

Function: set-process-coding-system process &optional decoding-system encoding-system

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.

Function: process-get process propname

This function returns the value of the propname property of process.

Function: process-put process propname value

This function sets the value of the propname property of process to value.

Function: process-plist process

This function returns the process plist of process.

Function: set-process-plist process plist

This function sets the process plist of process to plist.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.7 Sending Input to Processes

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 section Process Information). Otherwise, the coding system comes from coding-system-for-write, if that is non-nil; or else from the defaulting mechanism (@pxref{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, 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.

Function: process-send-string process string

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
Function: process-send-region process start end

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.)

Function: process-send-eof &optional process

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"
Function: process-running-child-p &optional process

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 is the subprocess is not active.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.8 Sending Signals to Processes

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.

Function: interrupt-process &optional process current-group

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.

Function: kill-process &optional process current-group

This function kills the process process by sending the signal SIGKILL. This signal kills the subprocess immediately, and cannot be handled by the subprocess.

Function: quit-process &optional process current-group

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.

Function: stop-process &optional process current-group

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.

Function: continue-process &optional process current-group

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.

Command: signal-process process signal

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 section Accessing Other Processes.

Sometimes, it is necessary to send a signal to a non-local asynchronous process. This is possible by writing an own interrupt-process implementation. This function must be added then to interrupt-process-functions.

Variable: interrupt-process-functions

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9 Receiving Output from Processes

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 section 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. If Emacs uses a pseudo-TTY (pty) for communication with the subprocess, then it is impossible to separate the standard output and standard error streams of the subprocess, because a pseudo-TTY has only one output channel. In that case, if you want to keep the output to those streams separate, you should redirect one of them to a file—for example, by using an appropriate shell command via start-process-shell-command or a similar function.

Alternatively, you could use the :stderr parameter with a non-nil value in a call to make-process (see section make-process) to make the destination of the error output separate from the standard output; in that case, Emacs will use pipes for communicating with the subprocess.

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 (@pxref{Waiting}), and in accept-process-output (see section Accepting Output from 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.

Variable: process-adaptive-read-buffering

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 (the default), as it will automatically delay reading from such processes, thus allowing them to produce more output before Emacs tries to read it.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9.1 Process Buffers

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 section 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 section Querying Before Exit). This confirmation is done by the function process-kill-buffer-query-function, which is run from kill-buffer-query-functions (@pxref{Killing Buffers}).

Function: process-buffer process

This function returns the associated buffer of the specified process.

(process-buffer (get-process "shell"))
     ⇒ #<buffer *shell*>
Function: process-mark process

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.

Function: set-process-buffer process buffer

This function sets the buffer associated with process to buffer. If buffer is nil, the process becomes associated with no buffer.

Function: get-buffer-process buffer-or-name

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 section 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.

Function: set-process-window-size process height width

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 (@pxref{Window Hooks}), 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.

User Option: window-adjust-process-window-size-function

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 section Process Information), its value overrides the global and buffer-local values of window-adjust-process-window-size-function.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9.2 Process Filter Functions

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 (see section Receiving Output from Processes).

The filter function can only be called when Emacs is waiting for something, because process output arrives only at such times. Emacs waits when reading terminal input (see the function waiting-for-user-input-p), in sit-for and sleep-for (@pxref{Waiting}), and in accept-process-output (see section Accepting Output from Processes).

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. @xref{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. @xref{Debugger}.

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 Emacs automatically saves and restores the match data while executing filter functions. @xref{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.

Function: set-process-filter process filter

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.

Function: process-filter process

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. @xref{Advising 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
")

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9.3 Decoding Process Output

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 section Process Information). Otherwise, the coding system comes from coding-system-for-read, if that is non-nil; or else from the defaulting mechanism (@pxref{Default Coding Systems}). If the text output by a process contains null bytes, Emacs by default uses no-conversion for it; see @ref{Lisp and Coding Systems, 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9.4 Accepting Output from Processes

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.

Function: accept-process-output &optional process seconds millisec just-this-one

This function allows Emacs to read pending output from processes. The output is given to their filter functions. If process is non-nil then this function does not return until some output has been received from process.

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. It returns nil if the timeout expired before output arrived.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.9.5 Processes and Threads

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.

Function: process-thread process

Return the thread to which process is locked. If process is unlocked, return nil.

Function: set-process-thread process thread

Set the locking thread of process to thread. thread may be nil, in which case the process is unlocked.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.10 Sentinels: Detecting Process Status Changes

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:

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 (@pxref{Waiting}), or accept-process-output (see section 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. @xref{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. @xref{Debugger}.

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. @xref{Match Data}.

Function: set-process-sentinel process sentinel

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>
Function: process-sentinel process

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. @xref{Advising Functions}.

Function: waiting-for-user-input-p

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.11 Querying Before Exit

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.

Function: process-query-on-exit-flag process

This returns the query flag of process.

Function: set-process-query-on-exit-flag process flag

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
User Option: confirm-kill-processes

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.12 Accessing Other Processes

In addition to accessing and manipulating processes that are subprocesses of the current Emacs session, Emacs Lisp programs can also access other processes running on the same machine. 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.

Function: list-system-processes

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.

Function: process-attributes pid

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. Values that are numbers can be either integer or floating point, depending on the magnitude of the value.

euid

The 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 (@pxref{User Identification}).

user

User name corresponding to the process’s effective user ID, a string.

egid

The group ID of the effective user ID, a number.

group

Group name corresponding to the effective user’s group ID, a string.

comm

The 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.

state

The 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.

ppid

The process ID of the parent process, a number.

pgrp

The process group ID of the process, a number.

sess

The session ID of the process. This is a number that is the process ID of the process’s session leader.

ttname

A 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’.

tpgid

The numerical process group ID of the foreground process group that uses the process’s terminal.

minflt

The number of minor page faults caused by the process since its beginning. (Minor page faults are those that don’t involve reading from disk.)

majflt

The 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.)

cminflt
cmajflt

Like minflt and majflt, but include the number of page faults for all the child processes of the given process.

utime

Time spent by the process in the user context, for running the application’s code. The corresponding value is in the (high low microsec picosec) format, the same format used by functions current-time (@pxref{Time of Day, current-time}) and file-attributes (@pxref{File Attributes}).

stime

Time spent by the process in the system (kernel) context, for processing system calls. The corresponding value is in the same format as for utime.

time

The sum of utime and stime. The corresponding value is in the same format as for utime.

cutime
cstime
ctime

Like utime, stime, and time, but include the times of all the child processes of the given process.

pri

The numerical priority of the process.

nice

The nice value of the process, a number. (Processes with smaller nice values get scheduled more favorably.)

thcount

The number of threads in the process.

start

The time when the process was started, in the same (high low microsec picosec) format used by file-attributes and current-time.

etime

The time elapsed since the process started, in the format (high low microsec picosec).

vsize

The virtual memory size of the process, measured in kilobytes.

rss

The size of the process’s resident set, the number of kilobytes occupied by the process in the machine’s physical memory.

pcpu

The percentage of the CPU time used by the process since it started. The corresponding value is a floating-point number between 0 and 100.

pmem

The 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.

args

The 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.13 Transaction Queues

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.

Function: tq-create process

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.

Function: tq-enqueue queue question regexp closure fn &optional delay-question

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.

Function: tq-close queue

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 section Process Filter Functions.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.14 Network Connections

Emacs Lisp programs can open stream (TCP) and datagram (UDP) network connections (see section 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 section 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 section 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 either built-in or external support. The built-in support uses 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 external support uses the ‘starttls.el’ library, which requires a helper utility such as gnutls-cli to be installed on the system. The open-network-stream function can transparently handle the details of creating encrypted connections for you, using whatever support is available.

Function: open-network-stream name buffer host service &rest parameters

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 boolean

If non-nil, try to make an asynchronous connection.

:type type

The type of connection. Options are:

plain

An ordinary, unencrypted connection.

tls
ssl

A TLS (Transport Layer Security) connection.

nil
network

Start 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.

starttls

As for nil, but if STARTTLS fails drop the connection.

shell

A shell connection.

:always-query-capabilities boolean

If non-nil, always ask for the server’s capabilities, even when doing a ‘plain’ connection.

:capability-command capability-command

Command string to query the host capabilities.

:end-of-command regexp
:end-of-capability regexp

Regular expression matching the end of a command, or the end of the command capability-command. The latter defaults to the former.

:starttls-function function

Function of one argument (the response to capability-command), which returns either nil, or the command to activate STARTTLS if supported.

:success regexp

Regular expression matching a successful STARTTLS negotiation.

:use-starttls-if-possible boolean

If non-nil, do opportunistic STARTTLS upgrades even if Emacs doesn’t have built-in TLS support.

:warn-unless-encrypted boolean

If non-nil, and :return-value is also non-nil, Emacs will warn if the connection isn’t encrypted. This is useful for protocols like IMAP and the like, where most users would expect the network traffic to be encrypted.

: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 Overview in The Auth-Source Manual). Only used for TLS or STARTTLS.

:return-list cons-or-nil

The return value of this function. If omitted or nil, return a process object. Otherwise, a cons of the form (process-object . plist), where plist has keywords:

:greeting string-or-nil

If non-nil, the greeting string returned by the host.

:capabilities string-or-nil

If non-nil, the host’s capability string.

:type symbol

The connection type: ‘plain’ or ‘tls’.

:shell-command string-or-nil

If the connection type is shell, this parameter will be interpreted as a format-spec string 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 could be something like ‘ssh gateway nc %s %p’.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.15 Network Servers

You create a server by calling make-network-process (see section 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:


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.16 Datagrams

A datagram connection communicates with individual packets rather than streams of data. Each call to process-send sends one datagram packet (see section 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.

Function: process-datagram-address process

If process is a datagram connection or server, this function returns its remote peer address.

Function: set-process-datagram-address process address

If process is a datagram connection or server, this function sets its remote peer address to address.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.17 Low-Level Network Access

You can also create network connections by operating at a lower level than that of open-network-stream, using make-network-process.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.17.1 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.

Function: make-network-process &rest args

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 name

Use the string name as the process name. It is modified if necessary to make it unique.

:type type

Specify 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-flag

If 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 host

Specify 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.

:service service

service specifies a port number to connect to; or, for a server, the port number to listen on. It should be a service name like ‘"http"’ that translates to a port number, or an integer like ‘80’ or an integer string like ‘"80"’ 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 family

family 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-socket

If 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-address

For 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-address

For 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:

  • - An IPv4 address is represented as a five-element vector of four 8-bit integers and one 16-bit integer [a b c d p] corresponding to numeric IPv4 address a.b.c.d and port number p.
  • - An IPv6 address is represented as a nine-element vector of 16-bit integers [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.
  • - A local address is represented as a string, which specifies the address in the local address space.
  • - An unsupported-family address is represented by a cons (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 bool

If 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-parameters

When 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 stopped

If stopped is non-nil, start the network connection or server in the stopped state.

:buffer buffer

Use buffer as the process buffer.

:coding coding

Use 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-flag

Initialize the process query flag to query-flag. See section Querying Before Exit.

:filter filter

Initialize the process filter to filter.

:filter-multibyte multibyte

If multibyte is non-nil, strings given to the process filter are multibyte, otherwise they are unibyte. The default is the default value of enable-multibyte-characters.

:sentinel sentinel

Initialize the process sentinel to sentinel.

:log log

Initialize 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 plist

Initialize the process plist to plist.

The original argument list, modified with the actual connection information, is available via the process-contact function.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.17.2 Network Options

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-name

If 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-flag

If 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-flag

If dontroute-flag is non-nil, the process can only send to hosts on the same network as the local host.

:keepalive keepalive-flag

If keepalive-flag is non-nil for a stream connection, enable exchange of low-level keep-alive messages.

:linger linger-arg

If 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-flag

If 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 priority

Set 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-flag

If 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.

Function: set-network-process-option process option value &optional no-error

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.17.3 Testing Availability of Network Features

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 keywordvalue 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 section Network Options. This form returns non-nil if that particular network option is supported by make-network-process (or set-network-process-option).


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.18 Misc Network Facilities

These additional functions are useful for creating and operating on network connections. Note that they are supported only on some systems.

Function: network-interface-list

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 (name . address). address has the same form as the local-address and remote-address arguments to make-network-process.

Function: network-interface-info ifname

This function returns information about the network interface named ifname. The value is a list of the form (addr bcast netmask hwaddr flags).

addr

The Internet protocol address.

bcast

The broadcast address.

netmask

The network mask.

hwaddr

The layer 2 address (Ethernet MAC address, for instance).

flags

The current flags of the interface.

Function: format-network-address address &optional omit-port

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.19 Communicating with Serial Ports

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.

Command: serial-term port speed

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.

Function: make-serial-process &rest args

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 port

This 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 speed

The 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 name

The name of the process. If name is not given, port will serve as the process name as well.

:buffer buffer

The 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 coding

If 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-flag

Initialize the process query flag to query-flag. See section Querying Before Exit. The flags defaults to nil if unspecified.

:stop bool

Start 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 filter

Install filter as the process filter.

:sentinel sentinel

Install sentinel as the process sentinel.

:plist plist

Install plist as the initial plist of the process.

:bytesize
:parity
:stopbits
:flowcontrol

These 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)
Function: serial-process-configure &rest args

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 port

Any 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 speed

The 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 bytesize

The number of bits per byte, which can be 7 or 8. If bytesize is not given or nil, it defaults to 8.

:parity parity

The 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 stopbits

The 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 flowcontrol

The 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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.20 Packing and Unpacking Byte Arrays

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.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.20.1 Describing Data Layout

To control unpacking and packing, you write a data layout specification, a special nested list describing named and typed fields. This specification controls the length of each field to be processed, and how to pack or unpack it. We normally keep bindat specs in variables whose names end in ‘-bindat-spec’; that kind of name is automatically recognized as risky.

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:

u8
byte

Unsigned byte, with length 1.

u16
word
short

Unsigned integer in network byte order, with length 2.

u24

Unsigned integer in network byte order, with length 3.

u32
dword
long

Unsigned integer in network byte order, with length 4. Note: These values may be limited by Emacs’s integer implementation limits.

u16r
u24r
u32r

Unsigned integer in little endian order, with length 2, 3 and 4, respectively.

str len

String of length len.

strz len

Zero-terminated string, in a fixed-size field with length len.

vec len [type]

Vector of len elements of type type, defaulting to bytes. The type is any of the simple types above, or another vector specified as a list of the form (vec len [type]).

ip

Four-byte vector representing an Internet address. For example: [127 0 0 1] for localhost.

bits len

List of set bits 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).

(eval form)

form is a Lisp expression evaluated at the moment the field is unpacked or packed. The result of the evaluation should be one of the above-listed type specifications.

For a fixed-size field, the length len is given as an integer specifying the number of bytes in the field.

When the length of a field is not fixed, it typically depends on the value of a preceding field. In this case, the length len can be given either as a list (name ...) identifying a field name in the format specified for bindat-get-field below, or by an expression (eval form) where form should evaluate to an integer, specifying the field length.

A field specification generally has the form ([name] handler), where name is optional. Don’t use names that are symbols meaningful as type specifications (above) or handler specifications (below), since that would be ambiguous. name can be a symbol or an expression (eval form), in which case form should evaluate to a symbol.

handler describes how to unpack or pack the field and can be one of the following:

type

Unpack/pack this field according to the type specification type.

eval form

Evaluate form, a Lisp expression, for side-effect only. If the field name is specified, the value is bound to that field name.

fill len

Skip len bytes. In packing, this leaves them unchanged, which normally means they remain zero. In unpacking, this means they are ignored.

align len

Skip to the next multiple of len bytes.

struct spec-name

Process spec-name as a sub-specification. This describes a structure nested within another structure.

union form (tag spec)…

Evaluate form, a Lisp expression, find the first tag that matches it, and process its associated data layout specification spec. Matching can occur in one of three ways:

repeat count field-specs

Process the field-specs recursively, in order, then repeat starting from the first one, processing all the specifications count times overall. The count is given using the same formats as a field length—if an eval form is used, it is evaluated just once. For correct operation, each specification in field-specs must include a name.

For the (eval form) forms used in a bindat specification, the form can access and update these dynamically bound variables during evaluation:

last

Value of the last field processed.

bindat-raw

The data as a byte array.

bindat-idx

Current index (within bindat-raw) for unpacking or packing.

struct

The alist containing the structured data that have been unpacked so far, or the entire structure being packed. You can use bindat-get-field to access specific fields of this structure.

count
index

Inside a repeat block, these contain the maximum number of repetitions (as specified by the count parameter), and the current repetition number (counting from 0). Setting count to zero will terminate the inner-most repeat block after the current repetition has completed.


[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.20.2 Functions to Unpack and Pack Bytes

In the following documentation, spec refers to a data layout specification, bindat-raw to a byte array, and struct to an alist representing unpacked field data.

Function: bindat-unpack spec bindat-raw &optional bindat-idx

This function unpacks data from the unibyte string or byte array bindat-raw according to spec. Normally, this starts unpacking at the beginning of the byte array, but if bindat-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.

Function: bindat-get-field struct &rest name

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, if name is (a b 2 c), that means to find field c in the third element of subfield b of field a. (This corresponds to struct.a.b[2].c in C.)

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.

Function: bindat-length spec struct

This function returns the total length of the data in struct, according to spec.

Function: bindat-pack spec struct &optional bindat-raw bindat-idx

This function returns a byte array packed according to spec from the data in the alist struct. It normally creates and fills a new byte array starting at the beginning. However, if bindat-raw is non-nil, it specifies a pre-allocated unibyte string or vector to pack into. If bindat-idx is non-nil, it specifies the starting offset for packing into bindat-raw.

When pre-allocating, you should make sure (length bindat-raw) meets or exceeds the total length to avoid an out-of-range error.

Function: bindat-ip-to-string ip

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"

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.20.3 Examples of Byte Unpacking and Packing

Here are two complete examples that use bindat.el. The first shows simple byte packing:

(require 'bindat)

(defun rfc868-payload ()
  (bindat-pack
   '((now-hi u16)
     (now-lo u16))
   ;; Emacs uses Unix epoch, while RFC868 epoch
   ;; is 1900-01-01 00:00:00, which is 2208988800
   ;; (or #x83aa7e80) seconds more.
   (let ((now (time-add nil '(#x83aa #x7e80))))
     `((now-hi . ,(car now))
       (now-lo . ,(cadr now))))))

(let ((s (rfc868-payload)))
  (list (multibyte-string-p s)
        (mapconcat (lambda (byte)
                     (format "%02x" byte))
                   s " ")
        (current-time-string)))
     ⇒ (nil "dc 6d 17 01" "Fri Mar 10 13:13:53 2017")

The following is an example of defining and unpacking a complex structure. Consider the following C structures:

struct header {
    unsigned long    dest_ip;
    unsigned long    src_ip;
    unsigned short   dest_port;
    unsigned short   src_port;
};

struct data {
    unsigned char    type;
    unsigned char    opcode;
    unsigned short   length;  /* in network byte order  */
    unsigned char    id[8];   /* null-terminated string  */
    unsigned char    data[/* (length + 3) & ~3 */];
};

struct packet {
    struct header    header;
    unsigned long    counters[2];  /* in little endian order  */
    unsigned char    items;
    unsigned char    filler[3];
    struct data      item[/* items */];

};

The corresponding data layout specification is:

(setq header-spec
      '((dest-ip   ip)
        (src-ip    ip)
        (dest-port u16)
        (src-port  u16)))

(setq data-spec
      '((type      u8)
        (opcode    u8)
        (length    u16)  ; network byte order
        (id        strz 8)
        (data      vec (length))
        (align     4)))

(setq packet-spec
      '((header    struct header-spec)
        (counters  vec 2 u32r)   ; little endian order
        (items     u8)
        (fill      3)
        (item      repeat (items)
                   (struct data-spec))))

A binary data representation is:

(setq binary-data
      [ 192 168 1 100 192 168 1 101 01 28 21 32
        160 134 1 0 5 1 0 0 2 0 0 0
        2 3 0 5 ?A ?B ?C ?D ?E ?F 0 0 1 2 3 4 5 0 0 0
        1 4 0 7 ?B ?C ?D ?E ?F ?G 0 0 6 7 8 9 10 11 12 0 ])

The corresponding decoded structure is:

(setq decoded (bindat-unpack packet-spec binary-data))
     ⇒
((header
  (dest-ip   . [192 168 1 100])
  (src-ip    . [192 168 1 101])
  (dest-port . 284)
  (src-port  . 5408))
 (counters . [100000 261])
 (items . 2)
 (item ((data . [1 2 3 4 5])
        (id . "ABCDEF")
        (length . 5)
        (opcode . 3)
        (type . 2))
       ((data . [6 7 8 9 10 11 12])
        (id . "BCDEFG")
        (length . 7)
        (opcode . 4)
        (type . 1))))

An example of fetching data from this structure:

(bindat-get-field decoded 'item 1 'id)
     ⇒ "BCDEFG"

[Top] [Contents] [Index] [ ? ]

Footnotes

(1)

On other systems, Emacs uses a Lisp emulation of ls; see @ref{Contents of Directories}.


[Top] [Contents] [Index] [ ? ]

About This Document

This document was generated on June 2, 2018 using texi2html.

The buttons in the navigation panels have the following meaning:

Button Name Go to From 1.2.3 go to
[ << ] FastBack Beginning of this chapter or previous chapter 1
[ < ] Back Previous section in reading order 1.2.2
[ Up ] Up Up section 1.2
[ > ] Forward Next section in reading order 1.2.4
[ >> ] FastForward Next chapter 2
[Top] Top Cover (top) of document  
[Contents] Contents Table of contents  
[Index] Index Index  
[ ? ] About About (help)  

where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:


This document was generated on June 2, 2018 using texi2html.