Document read-char-choice.
[bpt/emacs.git] / doc / lispref / processes.texi
CommitLineData
b8d4c8d0
GM
1@c -*-texinfo-*-
2@c This is part of the GNU Emacs Lisp Reference Manual.
acaf905b 3@c Copyright (C) 1990-1995, 1998-1999, 2001-2012
d24880de 4@c Free Software Foundation, Inc.
b8d4c8d0 5@c See the file elisp.texi for copying conditions.
6336d8c3 6@setfilename ../../info/processes
b8d4c8d0
GM
7@node Processes, Display, Abbrevs, Top
8@chapter Processes
9@cindex child process
10@cindex parent process
11@cindex subprocess
12@cindex process
13
14 In the terminology of operating systems, a @dfn{process} is a space in
15which a program can execute. Emacs runs in a process. Emacs Lisp
16programs can invoke other programs in processes of their own. These are
17called @dfn{subprocesses} or @dfn{child processes} of the Emacs process,
18which is their @dfn{parent process}.
19
20 A subprocess of Emacs may be @dfn{synchronous} or @dfn{asynchronous},
21depending on how it is created. When you create a synchronous
22subprocess, the Lisp program waits for the subprocess to terminate
23before continuing execution. When you create an asynchronous
24subprocess, it can run in parallel with the Lisp program. This kind of
25subprocess is represented within Emacs by a Lisp object which is also
26called a ``process.'' Lisp programs can use this object to communicate
27with the subprocess or to control it. For example, you can send
28signals, obtain status information, receive output from the process, or
29send input to it.
30
31@defun processp object
23dd4ecd
EZ
32This function returns @code{t} if @var{object} represents an Emacs
33subprocess, @code{nil} otherwise.
b8d4c8d0
GM
34@end defun
35
23dd4ecd
EZ
36 In addition to subprocesses of the current Emacs session, you can
37also access other processes running on your machine. @xref{System
38Processes}.
39
b8d4c8d0
GM
40@menu
41* Subprocess Creation:: Functions that start subprocesses.
42* Shell Arguments:: Quoting an argument to pass it to a shell.
43* Synchronous Processes:: Details of using synchronous subprocesses.
44* Asynchronous Processes:: Starting up an asynchronous subprocess.
45* Deleting Processes:: Eliminating an asynchronous subprocess.
46* Process Information:: Accessing run-status and other attributes.
47* Input to Processes:: Sending input to an asynchronous subprocess.
48* Signals to Processes:: Stopping, continuing or interrupting
49 an asynchronous subprocess.
50* Output from Processes:: Collecting output from an asynchronous subprocess.
51* Sentinels:: Sentinels run when process run-status changes.
52* Query Before Exit:: Whether to query if exiting will kill a process.
23dd4ecd 53* System Processes:: Accessing other processes running on your system.
d24880de 54* Transaction Queues:: Transaction-based communication with subprocesses.
b8d4c8d0
GM
55* Network:: Opening network connections.
56* Network Servers:: Network servers let Emacs accept net connections.
57* Datagrams:: UDP network connections.
58* Low-Level Network:: Lower-level but more general function
59 to create connections and servers.
d24880de 60* Misc Network:: Additional relevant functions for net connections.
c73e02fa 61* Serial Ports:: Communicating with serial ports.
b8d4c8d0
GM
62* Byte Packing:: Using bindat to pack and unpack binary data.
63@end menu
64
65@node Subprocess Creation
66@section Functions that Create Subprocesses
67
583d8b3c 68 There are three primitives that create a new subprocess in which to run
b8d4c8d0
GM
69a program. One of them, @code{start-process}, creates an asynchronous
70process and returns a process object (@pxref{Asynchronous Processes}).
71The other two, @code{call-process} and @code{call-process-region},
72create a synchronous process and do not return a process object
73(@pxref{Synchronous Processes}).
74
75 Synchronous and asynchronous processes are explained in the following
76sections. Since the three functions are all called in a similar
77fashion, their common arguments are described here.
78
79@cindex execute program
80@cindex @code{PATH} environment variable
81@cindex @code{HOME} environment variable
82 In all cases, the function's @var{program} argument specifies the
83program to be run. An error is signaled if the file is not found or
84cannot be executed. If the file name is relative, the variable
85@code{exec-path} contains a list of directories to search. Emacs
86initializes @code{exec-path} when it starts up, based on the value of
87the environment variable @code{PATH}. The standard file name
88constructs, @samp{~}, @samp{.}, and @samp{..}, are interpreted as
89usual in @code{exec-path}, but environment variable substitutions
90(@samp{$HOME}, etc.) are not recognized; use
91@code{substitute-in-file-name} to perform them (@pxref{File Name
92Expansion}). @code{nil} in this list refers to
93@code{default-directory}.
94
95 Executing a program can also try adding suffixes to the specified
96name:
97
98@defvar exec-suffixes
99This variable is a list of suffixes (strings) to try adding to the
100specified program file name. The list should include @code{""} if you
101want the name to be tried exactly as specified. The default value is
102system-dependent.
103@end defvar
104
105 @strong{Please note:} The argument @var{program} contains only the
106name of the program; it may not contain any command-line arguments. You
107must use @var{args} to provide those.
108
109 Each of the subprocess-creating functions has a @var{buffer-or-name}
110argument which specifies where the standard output from the program will
111go. It should be a buffer or a buffer name; if it is a buffer name,
112that will create the buffer if it does not already exist. It can also
113be @code{nil}, which says to discard the output unless a filter function
114handles it. (@xref{Filter Functions}, and @ref{Read and Print}.)
115Normally, you should avoid having multiple processes send output to the
116same buffer because their output would be intermixed randomly.
117
118@cindex program arguments
119 All three of the subprocess-creating functions have a @code{&rest}
120argument, @var{args}. The @var{args} must all be strings, and they are
121supplied to @var{program} as separate command line arguments. Wildcard
122characters and other shell constructs have no special meanings in these
123strings, since the strings are passed directly to the specified program.
124
125 The subprocess gets its current directory from the value of
126@code{default-directory} (@pxref{File Name Expansion}).
127
128@cindex environment variables, subprocesses
129 The subprocess inherits its environment from Emacs, but you can
130specify overrides for it with @code{process-environment}. @xref{System
131Environment}.
132
133@defvar exec-directory
134@pindex movemail
135The value of this variable is a string, the name of a directory that
136contains programs that come with GNU Emacs, programs intended for Emacs
137to invoke. The program @code{movemail} is an example of such a program;
138Rmail uses it to fetch new mail from an inbox.
139@end defvar
140
141@defopt exec-path
142The value of this variable is a list of directories to search for
143programs to run in subprocesses. Each element is either the name of a
144directory (i.e., a string), or @code{nil}, which stands for the default
145directory (which is the value of @code{default-directory}).
146@cindex program directories
147
148The value of @code{exec-path} is used by @code{call-process} and
149@code{start-process} when the @var{program} argument is not an absolute
150file name.
151@end defopt
152
153@node Shell Arguments
154@section Shell Arguments
155@cindex arguments for shell commands
156@cindex shell command arguments
157
158 Lisp programs sometimes need to run a shell and give it a command
159that contains file names that were specified by the user. These
160programs ought to be able to support any valid file name. But the shell
161gives special treatment to certain characters, and if these characters
162occur in the file name, they will confuse the shell. To handle these
163characters, use the function @code{shell-quote-argument}:
164
165@defun shell-quote-argument argument
166This function returns a string which represents, in shell syntax,
167an argument whose actual contents are @var{argument}. It should
168work reliably to concatenate the return value into a shell command
169and then pass it to a shell for execution.
170
171Precisely what this function does depends on your operating system. The
172function is designed to work with the syntax of your system's standard
173shell; if you use an unusual shell, you will need to redefine this
174function.
175
176@example
177;; @r{This example shows the behavior on GNU and Unix systems.}
178(shell-quote-argument "foo > bar")
179 @result{} "foo\\ \\>\\ bar"
180
181;; @r{This example shows the behavior on MS-DOS and MS-Windows.}
182(shell-quote-argument "foo > bar")
183 @result{} "\"foo > bar\""
184@end example
185
186Here's an example of using @code{shell-quote-argument} to construct
187a shell command:
188
189@example
190(concat "diff -c "
191 (shell-quote-argument oldfile)
192 " "
193 (shell-quote-argument newfile))
194@end example
195@end defun
196
3c73e30e
EZ
197@cindex quoting and unquoting command-line arguments
198@cindex minibuffer input, and command-line arguments
199@cindex @code{call-process}, command-line arguments from minibuffer
200@cindex @code{start-process}, command-line arguments from minibuffer
4bb49a92
EZ
201 The following two functions are useful for combining a list of
202individual command-line argument strings into a single string, and
203taking a string apart into a list of individual command-line
204arguments. These functions are mainly intended to be used for
205converting user input in the minibuffer, a Lisp string, into a list of
206string arguments to be passed to @code{call-process} or
3c73e30e
EZ
207@code{start-process}, or for the converting such lists of arguments in
208a single Lisp string to be presented in the minibuffer or echo area.
a873ee3d
EZ
209
210@defun split-string-and-unquote string &optional separators
211This function splits @var{string} into substrings at matches for the
212regular expression @var{separators}, like @code{split-string} does
0999039c
CY
213(@pxref{Creating Strings}); in addition, it removes quoting from the
214substrings. It then makes a list of the substrings and returns it.
a873ee3d 215
4185820c
CY
216If @var{separators} is omitted or @code{nil}, it defaults to
217@code{"\\s-+"}, which is a regular expression that matches one or more
218characters with whitespace syntax (@pxref{Syntax Class Table}).
a873ee3d 219
3c73e30e 220This function supports two types of quoting: enclosing a whole string
0999039c
CY
221in double quotes @code{"@dots{}"}, and quoting individual characters
222with a backslash escape @samp{\}. The latter is also used in Lisp
223strings, so this function can handle those as well.
a873ee3d
EZ
224@end defun
225
226@defun combine-and-quote-strings list-of-strings &optional separator
227This function concatenates @var{list-of-strings} into a single string,
0999039c
CY
228quoting each string as necessary. It also sticks the @var{separator}
229string between each pair of strings; if @var{separator} is omitted or
230@code{nil}, it defaults to @code{" "}. The return value is the
231resulting string.
a873ee3d
EZ
232
233The strings in @var{list-of-strings} that need quoting are those that
234include @var{separator} as their substring. Quoting a string encloses
235it in double quotes @code{"@dots{}"}. In the simplest case, if you
4bb49a92
EZ
236are consing a command from the individual command-line arguments,
237every argument that includes embedded blanks will be quoted.
a873ee3d
EZ
238@end defun
239
b8d4c8d0
GM
240@node Synchronous Processes
241@section Creating a Synchronous Process
242@cindex synchronous subprocess
243
244 After a @dfn{synchronous process} is created, Emacs waits for the
245process to terminate before continuing. Starting Dired on GNU or
246Unix@footnote{On other systems, Emacs uses a Lisp emulation of
247@code{ls}; see @ref{Contents of Directories}.} is an example of this: it
248runs @code{ls} in a synchronous process, then modifies the output
249slightly. Because the process is synchronous, the entire directory
250listing arrives in the buffer before Emacs tries to do anything with it.
251
252 While Emacs waits for the synchronous subprocess to terminate, the
253user can quit by typing @kbd{C-g}. The first @kbd{C-g} tries to kill
254the subprocess with a @code{SIGINT} signal; but it waits until the
255subprocess actually terminates before quitting. If during that time the
256user types another @kbd{C-g}, that kills the subprocess instantly with
257@code{SIGKILL} and quits immediately (except on MS-DOS, where killing
258other processes doesn't work). @xref{Quitting}.
259
260 The synchronous subprocess functions return an indication of how the
261process terminated.
262
263 The output from a synchronous subprocess is generally decoded using a
264coding system, much like text read from a file. The input sent to a
265subprocess by @code{call-process-region} is encoded using a coding
266system, much like text written into a file. @xref{Coding Systems}.
267
268@defun call-process program &optional infile destination display &rest args
b59a4335 269This function calls @var{program} and waits for it to finish.
b8d4c8d0 270
b59a4335 271The standard input for the new process comes from file @var{infile} if
b8d4c8d0
GM
272@var{infile} is not @code{nil}, and from the null device otherwise.
273The argument @var{destination} says where to put the process output.
274Here are the possibilities:
275
276@table @asis
277@item a buffer
278Insert the output in that buffer, before point. This includes both the
279standard output stream and the standard error stream of the process.
280
281@item a string
282Insert the output in a buffer with that name, before point.
283
284@item @code{t}
285Insert the output in the current buffer, before point.
286
287@item @code{nil}
288Discard the output.
289
290@item 0
291Discard the output, and return @code{nil} immediately without waiting
292for the subprocess to finish.
293
294In this case, the process is not truly synchronous, since it can run in
295parallel with Emacs; but you can think of it as synchronous in that
296Emacs is essentially finished with the subprocess as soon as this
297function returns.
298
299MS-DOS doesn't support asynchronous subprocesses, so this option doesn't
300work there.
301
1ef14cb4
LMI
302@item @code{(:file @var{file-name})}
303Send the output to the file name specified.
304
b8d4c8d0
GM
305@item @code{(@var{real-destination} @var{error-destination})}
306Keep the standard output stream separate from the standard error stream;
307deal with the ordinary output as specified by @var{real-destination},
308and dispose of the error output according to @var{error-destination}.
309If @var{error-destination} is @code{nil}, that means to discard the
310error output, @code{t} means mix it with the ordinary output, and a
311string specifies a file name to redirect error output into.
312
313You can't directly specify a buffer to put the error output in; that is
314too difficult to implement. But you can achieve this result by sending
315the error output to a temporary file and then inserting the file into a
316buffer.
317@end table
318
319If @var{display} is non-@code{nil}, then @code{call-process} redisplays
320the buffer as output is inserted. (However, if the coding system chosen
321for decoding output is @code{undecided}, meaning deduce the encoding
322from the actual data, then redisplay sometimes cannot continue once
323non-@acronym{ASCII} characters are encountered. There are fundamental
324reasons why it is hard to fix this; see @ref{Output from Processes}.)
325
326Otherwise the function @code{call-process} does no redisplay, and the
327results become visible on the screen only when Emacs redisplays that
328buffer in the normal course of events.
329
330The remaining arguments, @var{args}, are strings that specify command
331line arguments for the program.
332
333The value returned by @code{call-process} (unless you told it not to
334wait) indicates the reason for process termination. A number gives the
335exit status of the subprocess; 0 means success, and any other value
336means failure. If the process terminated with a signal,
337@code{call-process} returns a string describing the signal.
338
339In the examples below, the buffer @samp{foo} is current.
340
341@smallexample
342@group
343(call-process "pwd" nil t)
344 @result{} 0
345
346---------- Buffer: foo ----------
347/usr/user/lewis/manual
348---------- Buffer: foo ----------
349@end group
350
351@group
352(call-process "grep" nil "bar" nil "lewis" "/etc/passwd")
353 @result{} 0
354
355---------- Buffer: bar ----------
356lewis:5LTsHm66CSWKg:398:21:Bil Lewis:/user/lewis:/bin/csh
357
358---------- Buffer: bar ----------
359@end group
360@end smallexample
361
362Here is a good example of the use of @code{call-process}, which used to
363be found in the definition of @code{insert-directory}:
364
365@smallexample
366@group
367(call-process insert-directory-program nil t nil @var{switches}
368 (if full-directory-p
369 (concat (file-name-as-directory file) ".")
370 file))
371@end group
372@end smallexample
373@end defun
374
375@defun process-file program &optional infile buffer display &rest args
376This function processes files synchronously in a separate process. It
377is similar to @code{call-process} but may invoke a file handler based
378on the value of the variable @code{default-directory}. The current
379working directory of the subprocess is @code{default-directory}.
380
381The arguments are handled in almost the same way as for
382@code{call-process}, with the following differences:
383
384Some file handlers may not support all combinations and forms of the
385arguments @var{infile}, @var{buffer}, and @var{display}. For example,
386some file handlers might behave as if @var{display} were @code{nil},
387regardless of the value actually passed. As another example, some
388file handlers might not support separating standard output and error
389output by way of the @var{buffer} argument.
390
391If a file handler is invoked, it determines the program to run based
392on the first argument @var{program}. For instance, consider that a
393handler for remote files is invoked. Then the path that is used for
394searching the program might be different than @code{exec-path}.
395
396The second argument @var{infile} may invoke a file handler. The file
397handler could be different from the handler chosen for the
398@code{process-file} function itself. (For example,
399@code{default-directory} could be on a remote host, whereas
400@var{infile} is on another remote host. Or @code{default-directory}
401could be non-special, whereas @var{infile} is on a remote host.)
402
403If @var{buffer} is a list of the form @code{(@var{real-destination}
404@var{error-destination})}, and @var{error-destination} names a file,
405then the same remarks as for @var{infile} apply.
406
407The remaining arguments (@var{args}) will be passed to the process
408verbatim. Emacs is not involved in processing file names that are
409present in @var{args}. To avoid confusion, it may be best to avoid
410absolute file names in @var{args}, but rather to specify all file
411names as relative to @code{default-directory}. The function
412@code{file-relative-name} is useful for constructing such relative
413file names.
414@end defun
415
3691a0a6
MA
416@defvar process-file-side-effects
417This variable indicates, whether a call of @code{process-file} changes
418remote files.
419
420Per default, this variable is always set to @code{t}, meaning that a
421call of @code{process-file} could potentially change any file on a
422remote host. When set to @code{nil}, a file handler could optimize
91af3942 423its behavior with respect to remote file attributes caching.
3691a0a6
MA
424
425This variable should never be changed by @code{setq}. Instead of, it
426shall be set only by let-binding.
427@end defvar
428
b8d4c8d0
GM
429@defun call-process-region start end program &optional delete destination display &rest args
430This function sends the text from @var{start} to @var{end} as
431standard input to a process running @var{program}. It deletes the text
432sent if @var{delete} is non-@code{nil}; this is useful when
433@var{destination} is @code{t}, to insert the output in the current
434buffer in place of the input.
435
436The arguments @var{destination} and @var{display} control what to do
437with the output from the subprocess, and whether to update the display
438as it comes in. For details, see the description of
439@code{call-process}, above. If @var{destination} is the integer 0,
440@code{call-process-region} discards the output and returns @code{nil}
441immediately, without waiting for the subprocess to finish (this only
442works if asynchronous subprocesses are supported).
443
444The remaining arguments, @var{args}, are strings that specify command
445line arguments for the program.
446
447The return value of @code{call-process-region} is just like that of
448@code{call-process}: @code{nil} if you told it to return without
449waiting; otherwise, a number or string which indicates how the
450subprocess terminated.
451
452In the following example, we use @code{call-process-region} to run the
453@code{cat} utility, with standard input being the first five characters
454in buffer @samp{foo} (the word @samp{input}). @code{cat} copies its
455standard input into its standard output. Since the argument
456@var{destination} is @code{t}, this output is inserted in the current
457buffer.
458
459@smallexample
460@group
461---------- Buffer: foo ----------
462input@point{}
463---------- Buffer: foo ----------
464@end group
465
466@group
467(call-process-region 1 6 "cat" nil t)
468 @result{} 0
469
470---------- Buffer: foo ----------
471inputinput@point{}
472---------- Buffer: foo ----------
473@end group
474@end smallexample
475
476 The @code{shell-command-on-region} command uses
477@code{call-process-region} like this:
478
479@smallexample
480@group
481(call-process-region
482 start end
483 shell-file-name ; @r{Name of program.}
484 nil ; @r{Do not delete region.}
485 buffer ; @r{Send output to @code{buffer}.}
486 nil ; @r{No redisplay during output.}
487 "-c" command) ; @r{Arguments for the shell.}
488@end group
489@end smallexample
490@end defun
491
492@defun call-process-shell-command command &optional infile destination display &rest args
b59a4335
CY
493This function executes the shell command @var{command} synchronously.
494The final arguments @var{args} are additional arguments to add at the
495end of @var{command}. The other arguments are handled as in
496@code{call-process}.
b8d4c8d0
GM
497@end defun
498
499@defun process-file-shell-command command &optional infile destination display &rest args
500This function is like @code{call-process-shell-command}, but uses
501@code{process-file} internally. Depending on @code{default-directory},
502@var{command} can be executed also on remote hosts.
503@end defun
504
505@defun shell-command-to-string command
506This function executes @var{command} (a string) as a shell command,
507then returns the command's output as a string.
508@end defun
509
583d8b3c 510@defun process-lines program &rest args
b59a4335
CY
511This function runs @var{program}, waits for it to finish, and returns
512its output as a list of strings. Each string in the list holds a
513single line of text output by the program; the end-of-line characters
514are stripped from each line. The arguments beyond @var{program},
515@var{args}, are strings that specify command-line arguments with which
516to run the program.
583d8b3c
EZ
517
518If @var{program} exits with a non-zero exit status, this function
519signals an error.
520
521This function works by calling @code{call-process}, so program output
522is decoded in the same way as for @code{call-process}.
523@end defun
524
b8d4c8d0
GM
525@node Asynchronous Processes
526@section Creating an Asynchronous Process
527@cindex asynchronous subprocess
528
529 After an @dfn{asynchronous process} is created, Emacs and the subprocess
530both continue running immediately. The process thereafter runs
531in parallel with Emacs, and the two can communicate with each other
532using the functions described in the following sections. However,
533communication is only partially asynchronous: Emacs sends data to the
534process only when certain functions are called, and Emacs accepts data
535from the process only when Emacs is waiting for input or for a time
536delay.
537
538 Here we describe how to create an asynchronous process.
539
540@defun start-process name buffer-or-name program &rest args
541This function creates a new asynchronous subprocess and starts the
542program @var{program} running in it. It returns a process object that
543stands for the new subprocess in Lisp. The argument @var{name}
544specifies the name for the process object; if a process with this name
545already exists, then @var{name} is modified (by appending @samp{<1>},
546etc.) to be unique. The buffer @var{buffer-or-name} is the buffer to
547associate with the process.
548
549The remaining arguments, @var{args}, are strings that specify command
550line arguments for the program.
551
552In the example below, the first process is started and runs (rather,
553sleeps) for 100 seconds. Meanwhile, the second process is started, and
554given the name @samp{my-process<1>} for the sake of uniqueness. It
555inserts the directory listing at the end of the buffer @samp{foo},
556before the first process finishes. Then it finishes, and a message to
557that effect is inserted in the buffer. Much later, the first process
558finishes, and another message is inserted in the buffer for it.
559
560@smallexample
561@group
562(start-process "my-process" "foo" "sleep" "100")
563 @result{} #<process my-process>
564@end group
565
566@group
567(start-process "my-process" "foo" "ls" "-l" "/user/lewis/bin")
568 @result{} #<process my-process<1>>
569
570---------- Buffer: foo ----------
571total 2
572lrwxrwxrwx 1 lewis 14 Jul 22 10:12 gnuemacs --> /emacs
573-rwxrwxrwx 1 lewis 19 Jul 30 21:02 lemon
574
575Process my-process<1> finished
576
577Process my-process finished
578---------- Buffer: foo ----------
579@end group
580@end smallexample
581@end defun
582
583@defun start-file-process name buffer-or-name program &rest args
584Like @code{start-process}, this function starts a new asynchronous
585subprocess running @var{program} in it, and returns its process
586object---when @code{default-directory} is not a magic file name.
587
588If @code{default-directory} is magic, the function invokes its file
589handler instead. This handler ought to run @var{program}, perhaps on
590the local host, perhaps on a remote host that corresponds to
591@code{default-directory}. In the latter case, the local part of
592@code{default-directory} becomes the working directory of the process.
593
594This function does not try to invoke file name handlers for
595@var{program} or for the @var{program-args}.
596
597Depending on the implementation of the file handler, it might not be
598possible to apply @code{process-filter} or @code{process-sentinel} to
599the resulting process object (@pxref{Filter Functions}, @pxref{Sentinels}).
600
601Some file handlers may not support @code{start-file-process} (for
602example @code{ange-ftp-hook-function}). In such cases, the function
603does nothing and returns @code{nil}.
604@end defun
605
03a74b84 606@defun start-process-shell-command name buffer-or-name command
b8d4c8d0
GM
607This function is like @code{start-process} except that it uses a shell
608to execute the specified command. The argument @var{command} is a shell
03a74b84 609command name. The variable @code{shell-file-name} specifies which shell to
b8d4c8d0
GM
610use.
611
612The point of running a program through the shell, rather than directly
613with @code{start-process}, is so that you can employ shell features such
614as wildcards in the arguments. It follows that if you include an
615arbitrary user-specified arguments in the command, you should quote it
616with @code{shell-quote-argument} first, so that any special shell
617characters do @emph{not} have their special shell meanings. @xref{Shell
618Arguments}.
619@end defun
620
03a74b84 621@defun start-file-process-shell-command name buffer-or-name command
b8d4c8d0
GM
622This function is like @code{start-process-shell-command}, but uses
623@code{start-file-process} internally. By this, @var{command} can be
624executed also on remote hosts, depending on @code{default-directory}.
625@end defun
626
627@defvar process-connection-type
628@cindex pipes
629@cindex @acronym{PTY}s
630This variable controls the type of device used to communicate with
631asynchronous subprocesses. If it is non-@code{nil}, then @acronym{PTY}s are
632used, when available. Otherwise, pipes are used.
633
634@acronym{PTY}s are usually preferable for processes visible to the user, as
635in Shell mode, because they allow job control (@kbd{C-c}, @kbd{C-z},
636etc.) to work between the process and its children, whereas pipes do
637not. For subprocesses used for internal purposes by programs, it is
638often better to use a pipe, because they are more efficient. In
639addition, the total number of @acronym{PTY}s is limited on many systems and
640it is good not to waste them.
641
642The value of @code{process-connection-type} takes effect when
643@code{start-process} is called. So you can specify how to communicate
644with one subprocess by binding the variable around the call to
645@code{start-process}.
646
647@smallexample
648@group
649(let ((process-connection-type nil)) ; @r{Use a pipe.}
650 (start-process @dots{}))
651@end group
652@end smallexample
653
654To determine whether a given subprocess actually got a pipe or a
655@acronym{PTY}, use the function @code{process-tty-name} (@pxref{Process
656Information}).
657@end defvar
658
659@node Deleting Processes
660@section Deleting Processes
661@cindex deleting processes
662
663 @dfn{Deleting a process} disconnects Emacs immediately from the
664subprocess. Processes are deleted automatically after they terminate,
665but not necessarily right away. You can delete a process explicitly
666at any time. If you delete a terminated process explicitly before it
667is deleted automatically, no harm results. Deleting a running
668process sends a signal to terminate it (and its child processes if
669any), and calls the process sentinel if it has one. @xref{Sentinels}.
670
671 When a process is deleted, the process object itself continues to
672exist as long as other Lisp objects point to it. All the Lisp
673primitives that work on process objects accept deleted processes, but
674those that do I/O or send signals will report an error. The process
675mark continues to point to the same place as before, usually into a
676buffer where output from the process was being inserted.
677
678@defopt delete-exited-processes
679This variable controls automatic deletion of processes that have
680terminated (due to calling @code{exit} or to a signal). If it is
681@code{nil}, then they continue to exist until the user runs
682@code{list-processes}. Otherwise, they are deleted immediately after
683they exit.
684@end defopt
685
686@defun delete-process process
687This function deletes a process, killing it with a @code{SIGKILL}
688signal. The argument may be a process, the name of a process, a
689buffer, or the name of a buffer. (A buffer or buffer-name stands for
690the process that @code{get-buffer-process} returns.) Calling
691@code{delete-process} on a running process terminates it, updates the
692process status, and runs the sentinel (if any) immediately. If the
693process has already terminated, calling @code{delete-process} has no
694effect on its status, or on the running of its sentinel (which will
695happen sooner or later).
696
697@smallexample
698@group
699(delete-process "*shell*")
700 @result{} nil
701@end group
702@end smallexample
703@end defun
704
705@node Process Information
706@section Process Information
707
708 Several functions return information about processes.
709@code{list-processes} is provided for interactive use.
710
711@deffn Command list-processes &optional query-only
712This command displays a listing of all living processes. In addition,
713it finally deletes any process whose status was @samp{Exited} or
714@samp{Signaled}. It returns @code{nil}.
715
716If @var{query-only} is non-@code{nil} then it lists only processes
717whose query flag is non-@code{nil}. @xref{Query Before Exit}.
718@end deffn
719
720@defun process-list
721This function returns a list of all processes that have not been deleted.
722
723@smallexample
724@group
725(process-list)
726 @result{} (#<process display-time> #<process shell>)
727@end group
728@end smallexample
729@end defun
730
731@defun get-process name
732This function returns the process named @var{name}, or @code{nil} if
733there is none. An error is signaled if @var{name} is not a string.
734
735@smallexample
736@group
737(get-process "shell")
738 @result{} #<process shell>
739@end group
740@end smallexample
741@end defun
742
743@defun process-command process
744This function returns the command that was executed to start
745@var{process}. This is a list of strings, the first string being the
746program executed and the rest of the strings being the arguments that
747were given to the program.
748
749@smallexample
750@group
751(process-command (get-process "shell"))
752 @result{} ("/bin/csh" "-i")
753@end group
754@end smallexample
755@end defun
756
c73e02fa
GM
757@defun process-contact process &optional key
758
759This function returns information about how a network or serial
760process was set up. For a network process, when @var{key} is
761@code{nil}, it returns @code{(@var{hostname} @var{service})} which
762specifies what you connected to. For a serial process, when @var{key}
763is @code{nil}, it returns @code{(@var{port} @var{speed})}. For an
764ordinary child process, this function always returns @code{t}.
765
766If @var{key} is @code{t}, the value is the complete status information
767for the connection, server, or serial port; that is, the list of
768keywords and values specified in @code{make-network-process} or
769@code{make-serial-process}, except that some of the values represent
770the current status instead of what you specified.
771
772For a network process:
773
774@table @code
775@item :buffer
776The associated value is the process buffer.
777@item :filter
778The associated value is the process filter function.
779@item :sentinel
780The associated value is the process sentinel function.
781@item :remote
782In a connection, the address in internal format of the remote peer.
783@item :local
784The local address, in internal format.
785@item :service
786In a server, if you specified @code{t} for @var{service},
787this value is the actual port number.
788@end table
789
790@code{:local} and @code{:remote} are included even if they were not
791specified explicitly in @code{make-network-process}.
792
793For a serial process, see @code{make-serial-process} and
794@code{serial-process-configure} for a list of keys.
795
796If @var{key} is a keyword, the function returns the value corresponding
797to that keyword.
798@end defun
799
b8d4c8d0
GM
800@defun process-id process
801This function returns the @acronym{PID} of @var{process}. This is an
802integer that distinguishes the process @var{process} from all other
803processes running on the same computer at the current time. The
804@acronym{PID} of a process is chosen by the operating system kernel when the
805process is started and remains constant as long as the process exists.
806@end defun
807
808@defun process-name process
809This function returns the name of @var{process}.
810@end defun
811
812@defun process-status process-name
813This function returns the status of @var{process-name} as a symbol.
170ddd97
CY
814The argument @var{process-name} must be a process, a buffer, or a
815process name (a string).
b8d4c8d0
GM
816
817The possible values for an actual subprocess are:
818
819@table @code
820@item run
821for a process that is running.
822@item stop
823for a process that is stopped but continuable.
824@item exit
825for a process that has exited.
826@item signal
827for a process that has received a fatal signal.
828@item open
829for a network connection that is open.
830@item closed
831for a network connection that is closed. Once a connection
832is closed, you cannot reopen it, though you might be able to open
833a new connection to the same place.
834@item connect
835for a non-blocking connection that is waiting to complete.
836@item failed
837for a non-blocking connection that has failed to complete.
838@item listen
839for a network server that is listening.
840@item nil
841if @var{process-name} is not the name of an existing process.
842@end table
843
844@smallexample
845@group
b8d4c8d0
GM
846(process-status (get-buffer "*shell*"))
847 @result{} run
848@end group
849@group
850x
851 @result{} #<process xx<1>>
852(process-status x)
853 @result{} exit
854@end group
855@end smallexample
856
857For a network connection, @code{process-status} returns one of the symbols
858@code{open} or @code{closed}. The latter means that the other side
859closed the connection, or Emacs did @code{delete-process}.
860@end defun
861
b96e6cde 862@defun process-live-p process
bcd54f83
LMI
863This function returns nin-@code{nil} if @var{process} is alive. A
864process is considered alive if its status is @code{run}, @code{open},
865@code{listen}, @code{connect} or @code{stop}.
866@end defun
867
c73e02fa
GM
868@defun process-type process
869This function returns the symbol @code{network} for a network
870connection or server, @code{serial} for a serial port connection, or
871@code{real} for a real subprocess.
872@end defun
873
b8d4c8d0
GM
874@defun process-exit-status process
875This function returns the exit status of @var{process} or the signal
876number that killed it. (Use the result of @code{process-status} to
877determine which of those it is.) If @var{process} has not yet
878terminated, the value is 0.
879@end defun
880
881@defun process-tty-name process
882This function returns the terminal name that @var{process} is using for
883its communication with Emacs---or @code{nil} if it is using pipes
884instead of a terminal (see @code{process-connection-type} in
bace45fe
MA
885@ref{Asynchronous Processes}). If @var{process} represents a program
886running on a remote host, the terminal name used by that program on
887the remote host is provided as process property @code{remote-tty}.
b8d4c8d0
GM
888@end defun
889
890@defun process-coding-system process
891@anchor{Coding systems for a subprocess}
892This function returns a cons cell describing the coding systems in use
893for decoding output from @var{process} and for encoding input to
894@var{process} (@pxref{Coding Systems}). The value has this form:
895
896@example
897(@var{coding-system-for-decoding} . @var{coding-system-for-encoding})
898@end example
899@end defun
900
901@defun set-process-coding-system process &optional decoding-system encoding-system
902This function specifies the coding systems to use for subsequent output
903from and input to @var{process}. It will use @var{decoding-system} to
904decode subprocess output, and @var{encoding-system} to encode subprocess
905input.
906@end defun
907
908 Every process also has a property list that you can use to store
909miscellaneous values associated with the process.
910
911@defun process-get process propname
912This function returns the value of the @var{propname} property
913of @var{process}.
914@end defun
915
916@defun process-put process propname value
917This function sets the value of the @var{propname} property
918of @var{process} to @var{value}.
919@end defun
920
921@defun process-plist process
922This function returns the process plist of @var{process}.
923@end defun
924
925@defun set-process-plist process plist
926This function sets the process plist of @var{process} to @var{plist}.
927@end defun
928
929@node Input to Processes
930@section Sending Input to Processes
931@cindex process input
932
933 Asynchronous subprocesses receive input when it is sent to them by
934Emacs, which is done with the functions in this section. You must
935specify the process to send input to, and the input data to send. The
936data appears on the ``standard input'' of the subprocess.
937
938 Some operating systems have limited space for buffered input in a
939@acronym{PTY}. On these systems, Emacs sends an @acronym{EOF}
940periodically amidst the other characters, to force them through. For
941most programs, these @acronym{EOF}s do no harm.
942
943 Subprocess input is normally encoded using a coding system before the
944subprocess receives it, much like text written into a file. You can use
945@code{set-process-coding-system} to specify which coding system to use
946(@pxref{Process Information}). Otherwise, the coding system comes from
947@code{coding-system-for-write}, if that is non-@code{nil}; or else from
948the defaulting mechanism (@pxref{Default Coding Systems}).
949
950 Sometimes the system is unable to accept input for that process,
951because the input buffer is full. When this happens, the send functions
952wait a short while, accepting output from subprocesses, and then try
953again. This gives the subprocess a chance to read more of its pending
954input and make space in the buffer. It also allows filters, sentinels
955and timers to run---so take account of that in writing your code.
956
957 In these functions, the @var{process} argument can be a process or
958the name of a process, or a buffer or buffer name (which stands
959for a process via @code{get-buffer-process}). @code{nil} means
960the current buffer's process.
961
962@defun process-send-string process string
963This function sends @var{process} the contents of @var{string} as
964standard input. If it is @code{nil}, the current buffer's process is used.
965
966 The function returns @code{nil}.
967
968@smallexample
969@group
970(process-send-string "shell<1>" "ls\n")
971 @result{} nil
972@end group
973
974
975@group
976---------- Buffer: *shell* ----------
977...
978introduction.texi syntax-tables.texi~
979introduction.texi~ text.texi
980introduction.txt text.texi~
981...
982---------- Buffer: *shell* ----------
983@end group
984@end smallexample
985@end defun
986
987@defun process-send-region process start end
988This function sends the text in the region defined by @var{start} and
989@var{end} as standard input to @var{process}.
990
991An error is signaled unless both @var{start} and @var{end} are
992integers or markers that indicate positions in the current buffer. (It
993is unimportant which number is larger.)
994@end defun
995
996@defun process-send-eof &optional process
997This function makes @var{process} see an end-of-file in its
998input. The @acronym{EOF} comes after any text already sent to it.
999
1000The function returns @var{process}.
1001
1002@smallexample
1003@group
1004(process-send-eof "shell")
1005 @result{} "shell"
1006@end group
1007@end smallexample
1008@end defun
1009
106e6894
CY
1010@defun process-running-child-p &optional process
1011This function will tell you whether a @var{process} has given control of
b8d4c8d0
GM
1012its terminal to its own child process. The value is @code{t} if this is
1013true, or if Emacs cannot tell; it is @code{nil} if Emacs can be certain
1014that this is not so.
1015@end defun
1016
1017@node Signals to Processes
1018@section Sending Signals to Processes
1019@cindex process signals
1020@cindex sending signals
1021@cindex signals
1022
1023 @dfn{Sending a signal} to a subprocess is a way of interrupting its
1024activities. There are several different signals, each with its own
1025meaning. The set of signals and their names is defined by the operating
1026system. For example, the signal @code{SIGINT} means that the user has
1027typed @kbd{C-c}, or that some analogous thing has happened.
1028
1029 Each signal has a standard effect on the subprocess. Most signals
1030kill the subprocess, but some stop or resume execution instead. Most
1031signals can optionally be handled by programs; if the program handles
1032the signal, then we can say nothing in general about its effects.
1033
1034 You can send signals explicitly by calling the functions in this
1035section. Emacs also sends signals automatically at certain times:
1036killing a buffer sends a @code{SIGHUP} signal to all its associated
1037processes; killing Emacs sends a @code{SIGHUP} signal to all remaining
1038processes. (@code{SIGHUP} is a signal that usually indicates that the
1039user hung up the phone.)
1040
1041 Each of the signal-sending functions takes two optional arguments:
1042@var{process} and @var{current-group}.
1043
1044 The argument @var{process} must be either a process, a process
1045name, a buffer, a buffer name, or @code{nil}. A buffer or buffer name
1046stands for a process through @code{get-buffer-process}. @code{nil}
1047stands for the process associated with the current buffer. An error
1048is signaled if @var{process} does not identify a process.
1049
1050 The argument @var{current-group} is a flag that makes a difference
1051when you are running a job-control shell as an Emacs subprocess. If it
1052is non-@code{nil}, then the signal is sent to the current process-group
1053of the terminal that Emacs uses to communicate with the subprocess. If
1054the process is a job-control shell, this means the shell's current
1055subjob. If it is @code{nil}, the signal is sent to the process group of
1056the immediate subprocess of Emacs. If the subprocess is a job-control
1057shell, this is the shell itself.
1058
1059 The flag @var{current-group} has no effect when a pipe is used to
1060communicate with the subprocess, because the operating system does not
1061support the distinction in the case of pipes. For the same reason,
1062job-control shells won't work when a pipe is used. See
1063@code{process-connection-type} in @ref{Asynchronous Processes}.
1064
1065@defun interrupt-process &optional process current-group
1066This function interrupts the process @var{process} by sending the
1067signal @code{SIGINT}. Outside of Emacs, typing the ``interrupt
1068character'' (normally @kbd{C-c} on some systems, and @code{DEL} on
1069others) sends this signal. When the argument @var{current-group} is
1070non-@code{nil}, you can think of this function as ``typing @kbd{C-c}''
1071on the terminal by which Emacs talks to the subprocess.
1072@end defun
1073
1074@defun kill-process &optional process current-group
1075This function kills the process @var{process} by sending the
1076signal @code{SIGKILL}. This signal kills the subprocess immediately,
1077and cannot be handled by the subprocess.
1078@end defun
1079
1080@defun quit-process &optional process current-group
1081This function sends the signal @code{SIGQUIT} to the process
1082@var{process}. This signal is the one sent by the ``quit
1083character'' (usually @kbd{C-b} or @kbd{C-\}) when you are not inside
1084Emacs.
1085@end defun
1086
1087@defun stop-process &optional process current-group
1088This function stops the process @var{process} by sending the
1089signal @code{SIGTSTP}. Use @code{continue-process} to resume its
1090execution.
1091
1092Outside of Emacs, on systems with job control, the ``stop character''
1093(usually @kbd{C-z}) normally sends this signal. When
1094@var{current-group} is non-@code{nil}, you can think of this function as
1095``typing @kbd{C-z}'' on the terminal Emacs uses to communicate with the
1096subprocess.
1097@end defun
1098
1099@defun continue-process &optional process current-group
1100This function resumes execution of the process @var{process} by sending
1101it the signal @code{SIGCONT}. This presumes that @var{process} was
1102stopped previously.
1103@end defun
1104
b8d4c8d0
GM
1105@defun signal-process process signal
1106This function sends a signal to process @var{process}. The argument
1107@var{signal} specifies which signal to send; it should be an integer.
1108
1109The @var{process} argument can be a system process @acronym{ID}; that
1110allows you to send signals to processes that are not children of
23dd4ecd 1111Emacs. @xref{System Processes}.
b8d4c8d0
GM
1112@end defun
1113
1114@node Output from Processes
1115@section Receiving Output from Processes
1116@cindex process output
1117@cindex output from processes
1118
1119 There are two ways to receive the output that a subprocess writes to
1120its standard output stream. The output can be inserted in a buffer,
1121which is called the associated buffer of the process, or a function
1122called the @dfn{filter function} can be called to act on the output. If
1123the process has no buffer and no filter function, its output is
1124discarded.
1125
1126 When a subprocess terminates, Emacs reads any pending output,
1127then stops reading output from that subprocess. Therefore, if the
1128subprocess has children that are still live and still producing
1129output, Emacs won't receive that output.
1130
1131 Output from a subprocess can arrive only while Emacs is waiting: when
1132reading terminal input, in @code{sit-for} and @code{sleep-for}
1133(@pxref{Waiting}), and in @code{accept-process-output} (@pxref{Accepting
1134Output}). This minimizes the problem of timing errors that usually
1135plague parallel programming. For example, you can safely create a
1136process and only then specify its buffer or filter function; no output
1137can arrive before you finish, if the code in between does not call any
1138primitive that waits.
1139
1140@defvar process-adaptive-read-buffering
1141On some systems, when Emacs reads the output from a subprocess, the
1142output data is read in very small blocks, potentially resulting in
1143very poor performance. This behavior can be remedied to some extent
1144by setting the variable @var{process-adaptive-read-buffering} to a
1145non-@code{nil} value (the default), as it will automatically delay reading
1146from such processes, thus allowing them to produce more output before
1147Emacs tries to read it.
1148@end defvar
1149
1150 It is impossible to separate the standard output and standard error
1151streams of the subprocess, because Emacs normally spawns the subprocess
1152inside a pseudo-TTY, and a pseudo-TTY has only one output channel. If
1153you want to keep the output to those streams separate, you should
1154redirect one of them to a file---for example, by using an appropriate
1155shell command.
1156
1157@menu
1158* Process Buffers:: If no filter, output is put in a buffer.
1159* Filter Functions:: Filter functions accept output from the process.
1160* Decoding Output:: Filters can get unibyte or multibyte strings.
1161* Accepting Output:: How to wait until process output arrives.
1162@end menu
1163
1164@node Process Buffers
1165@subsection Process Buffers
1166
1167 A process can (and usually does) have an @dfn{associated buffer},
1168which is an ordinary Emacs buffer that is used for two purposes: storing
1169the output from the process, and deciding when to kill the process. You
1170can also use the buffer to identify a process to operate on, since in
1171normal practice only one process is associated with any given buffer.
1172Many applications of processes also use the buffer for editing input to
1173be sent to the process, but this is not built into Emacs Lisp.
1174
1175 Unless the process has a filter function (@pxref{Filter Functions}),
1176its output is inserted in the associated buffer. The position to insert
1177the output is determined by the @code{process-mark}, which is then
1178updated to point to the end of the text just inserted. Usually, but not
1179always, the @code{process-mark} is at the end of the buffer.
1180
16d1ff5f
CY
1181@findex process-kill-buffer-query-function
1182 Killing the associated buffer of a process also kills the process.
1183Emacs asks for confirmation first, if the process's
1184@code{process-query-on-exit-flag} is non-@code{nil} (@pxref{Query
1185Before Exit}). This confirmation is done by the function
1186@code{process-kill-buffer-query-function}, which is run from
1187@code{kill-buffer-query-functions} (@pxref{Killing Buffers}).
1188
b8d4c8d0
GM
1189@defun process-buffer process
1190This function returns the associated buffer of the process
1191@var{process}.
1192
1193@smallexample
1194@group
1195(process-buffer (get-process "shell"))
1196 @result{} #<buffer *shell*>
1197@end group
1198@end smallexample
1199@end defun
1200
1201@defun process-mark process
1202This function returns the process marker for @var{process}, which is the
1203marker that says where to insert output from the process.
1204
1205If @var{process} does not have a buffer, @code{process-mark} returns a
1206marker that points nowhere.
1207
1208Insertion of process output in a buffer uses this marker to decide where
1209to insert, and updates it to point after the inserted text. That is why
1210successive batches of output are inserted consecutively.
1211
1212Filter functions normally should use this marker in the same fashion
1213as is done by direct insertion of output in the buffer. A good
1214example of a filter function that uses @code{process-mark} is found at
1215the end of the following section.
1216
1217When the user is expected to enter input in the process buffer for
1218transmission to the process, the process marker separates the new input
1219from previous output.
1220@end defun
1221
1222@defun set-process-buffer process buffer
1223This function sets the buffer associated with @var{process} to
1224@var{buffer}. If @var{buffer} is @code{nil}, the process becomes
1225associated with no buffer.
1226@end defun
1227
1228@defun get-buffer-process buffer-or-name
1229This function returns a nondeleted process associated with the buffer
1230specified by @var{buffer-or-name}. If there are several processes
1231associated with it, this function chooses one (currently, the one most
1232recently created, but don't count on that). Deletion of a process
1233(see @code{delete-process}) makes it ineligible for this function to
1234return.
1235
1236It is usually a bad idea to have more than one process associated with
1237the same buffer.
1238
1239@smallexample
1240@group
1241(get-buffer-process "*shell*")
1242 @result{} #<process shell>
1243@end group
1244@end smallexample
1245
1246Killing the process's buffer deletes the process, which kills the
1247subprocess with a @code{SIGHUP} signal (@pxref{Signals to Processes}).
1248@end defun
1249
1250@node Filter Functions
1251@subsection Process Filter Functions
1252@cindex filter function
1253@cindex process filter
1254
1255 A process @dfn{filter function} is a function that receives the
1256standard output from the associated process. If a process has a filter,
1257then @emph{all} output from that process is passed to the filter. The
1258process buffer is used directly for output from the process only when
1259there is no filter.
1260
1261 The filter function can only be called when Emacs is waiting for
1262something, because process output arrives only at such times. Emacs
1263waits when reading terminal input, in @code{sit-for} and
1264@code{sleep-for} (@pxref{Waiting}), and in @code{accept-process-output}
1265(@pxref{Accepting Output}).
1266
1267 A filter function must accept two arguments: the associated process
1268and a string, which is output just received from it. The function is
1269then free to do whatever it chooses with the output.
1270
1271 Quitting is normally inhibited within a filter function---otherwise,
1272the effect of typing @kbd{C-g} at command level or to quit a user
1273command would be unpredictable. If you want to permit quitting inside
1274a filter function, bind @code{inhibit-quit} to @code{nil}. In most
1275cases, the right way to do this is with the macro
1276@code{with-local-quit}. @xref{Quitting}.
1277
1278 If an error happens during execution of a filter function, it is
1279caught automatically, so that it doesn't stop the execution of whatever
1280program was running when the filter function was started. However, if
1281@code{debug-on-error} is non-@code{nil}, the error-catching is turned
1282off. This makes it possible to use the Lisp debugger to debug the
1283filter function. @xref{Debugger}.
1284
1285 Many filter functions sometimes or always insert the text in the
1286process's buffer, mimicking the actions of Emacs when there is no
1287filter. Such filter functions need to use @code{set-buffer} in order to
1288be sure to insert in that buffer. To avoid setting the current buffer
1289semipermanently, these filter functions must save and restore the
78e33835
CY
1290current buffer. They should also check whether the buffer is still
1291alive, update the process marker, and in some cases update the value
1292of point. Here is how to do these things:
b8d4c8d0
GM
1293
1294@smallexample
1295@group
1296(defun ordinary-insertion-filter (proc string)
78e33835
CY
1297 (when (buffer-live-p (process-buffer proc))
1298 (with-current-buffer (process-buffer proc)
1299 (let ((moving (= (point) (process-mark proc))))
b8d4c8d0
GM
1300@end group
1301@group
78e33835 1302 (save-excursion
1e5c1c80 1303 ;; @r{Insert the text, advancing the process marker.}
78e33835
CY
1304 (goto-char (process-mark proc))
1305 (insert string)
1306 (set-marker (process-mark proc) (point)))
1307 (if moving (goto-char (process-mark proc)))))))
b8d4c8d0
GM
1308@end group
1309@end smallexample
1310
1311@noindent
1312The reason to use @code{with-current-buffer}, rather than using
1313@code{save-excursion} to save and restore the current buffer, is so as
1314to preserve the change in point made by the second call to
1315@code{goto-char}.
1316
1317 To make the filter force the process buffer to be visible whenever new
1318text arrives, insert the following line just before the
1319@code{with-current-buffer} construct:
1320
1321@smallexample
1322(display-buffer (process-buffer proc))
1323@end smallexample
1324
1325 To force point to the end of the new output, no matter where it was
1326previously, eliminate the variable @code{moving} and call
1327@code{goto-char} unconditionally.
1328
1329 In earlier Emacs versions, every filter function that did regular
1330expression searching or matching had to explicitly save and restore the
1331match data. Now Emacs does this automatically for filter functions;
1332they never need to do it explicitly. @xref{Match Data}.
1333
b8d4c8d0
GM
1334 The output to the function may come in chunks of any size. A program
1335that produces the same output twice in a row may send it as one batch of
1336200 characters one time, and five batches of 40 characters the next. If
1337the filter looks for certain text strings in the subprocess output, make
1338sure to handle the case where one of these strings is split across two
fd211f0b
CY
1339or more batches of output; one way to do this is to insert the
1340received text into a temporary buffer, which can then be searched.
b8d4c8d0
GM
1341
1342@defun set-process-filter process filter
1343This function gives @var{process} the filter function @var{filter}. If
1344@var{filter} is @code{nil}, it gives the process no filter.
1345@end defun
1346
1347@defun process-filter process
1348This function returns the filter function of @var{process}, or @code{nil}
1349if it has none.
1350@end defun
1351
1352 Here is an example of use of a filter function:
1353
1354@smallexample
1355@group
1356(defun keep-output (process output)
1357 (setq kept (cons output kept)))
1358 @result{} keep-output
1359@end group
1360@group
1361(setq kept nil)
1362 @result{} nil
1363@end group
1364@group
1365(set-process-filter (get-process "shell") 'keep-output)
1366 @result{} keep-output
1367@end group
1368@group
1369(process-send-string "shell" "ls ~/other\n")
1370 @result{} nil
1371kept
1372 @result{} ("lewis@@slug[8] % "
1373@end group
1374@group
1375"FINAL-W87-SHORT.MSS backup.otl kolstad.mss~
1376address.txt backup.psf kolstad.psf
1377backup.bib~ david.mss resume-Dec-86.mss~
1378backup.err david.psf resume-Dec.psf
1379backup.mss dland syllabus.mss
1380"
1381"#backups.mss# backup.mss~ kolstad.mss
1382")
1383@end group
1384@end smallexample
1385
1386@ignore @c The code in this example doesn't show the right way to do things.
1387Here is another, more realistic example, which demonstrates how to use
1388the process mark to do insertion in the same fashion as is done when
1389there is no filter function:
1390
1391@smallexample
1392@group
1393;; @r{Insert input in the buffer specified by @code{my-shell-buffer}}
1394;; @r{and make sure that buffer is shown in some window.}
1395(defun my-process-filter (proc str)
1396 (let ((cur (selected-window))
1397 (pop-up-windows t))
1398 (pop-to-buffer my-shell-buffer)
1399@end group
1400@group
1401 (goto-char (point-max))
1402 (insert str)
1403 (set-marker (process-mark proc) (point-max))
1404 (select-window cur)))
1405@end group
1406@end smallexample
1407@end ignore
1408
1409@node Decoding Output
1410@subsection Decoding Process Output
1411@cindex decode process output
1412
1413 When Emacs writes process output directly into a multibyte buffer,
1414it decodes the output according to the process output coding system.
1415If the coding system is @code{raw-text} or @code{no-conversion}, Emacs
1416converts the unibyte output to multibyte using
1417@code{string-to-multibyte}, and inserts the resulting multibyte text.
1418
1419 You can use @code{set-process-coding-system} to specify which coding
1420system to use (@pxref{Process Information}). Otherwise, the coding
1421system comes from @code{coding-system-for-read}, if that is
1422non-@code{nil}; or else from the defaulting mechanism (@pxref{Default
3355f04d
EZ
1423Coding Systems}). If the text output by a process contains null
1424bytes, Emacs by default uses @code{no-conversion} for it; see
1425@ref{Lisp and Coding Systems, inhibit-null-byte-detection}, for how to
1426control this behavior.
b8d4c8d0
GM
1427
1428 @strong{Warning:} Coding systems such as @code{undecided} which
1429determine the coding system from the data do not work entirely
1430reliably with asynchronous subprocess output. This is because Emacs
1431has to process asynchronous subprocess output in batches, as it
1432arrives. Emacs must try to detect the proper coding system from one
1433batch at a time, and this does not always work. Therefore, if at all
1434possible, specify a coding system that determines both the character
1435code conversion and the end of line conversion---that is, one like
1436@code{latin-1-unix}, rather than @code{undecided} or @code{latin-1}.
1437
4972c361
SM
1438@c Let's keep the index entries that were there for
1439@c set-process-filter-multibyte and process-filter-multibyte-p,
b8d4c8d0
GM
1440@cindex filter multibyte flag, of process
1441@cindex process filter multibyte flag
1442 When Emacs calls a process filter function, it provides the process
1443output as a multibyte string or as a unibyte string according to the
4972c361
SM
1444process's filter coding system. Emacs
1445decodes the output according to the process output coding system,
1446which usually produces a multibyte string, except for coding systems
1447such as @code{binary} and @code{raw-text}
b8d4c8d0
GM
1448
1449@node Accepting Output
1450@subsection Accepting Output from Processes
1451@cindex accept input from processes
1452
1453 Output from asynchronous subprocesses normally arrives only while
1454Emacs is waiting for some sort of external event, such as elapsed time
1455or terminal input. Occasionally it is useful in a Lisp program to
1456explicitly permit output to arrive at a specific point, or even to wait
1457until output arrives from a process.
1458
1459@defun accept-process-output &optional process seconds millisec just-this-one
1460This function allows Emacs to read pending output from processes. The
1461output is inserted in the associated buffers or given to their filter
1462functions. If @var{process} is non-@code{nil} then this function does
1463not return until some output has been received from @var{process}.
1464
1465@c Emacs 19 feature
1466The arguments @var{seconds} and @var{millisec} let you specify timeout
1467periods. The former specifies a period measured in seconds and the
1468latter specifies one measured in milliseconds. The two time periods
1469thus specified are added together, and @code{accept-process-output}
1470returns after that much time, whether or not there has been any
1471subprocess output.
1472
1473The argument @var{millisec} is semi-obsolete nowadays because
1474@var{seconds} can be a floating point number to specify waiting a
1475fractional number of seconds. If @var{seconds} is 0, the function
1476accepts whatever output is pending but does not wait.
1477
1478@c Emacs 22.1 feature
1479If @var{process} is a process, and the argument @var{just-this-one} is
1480non-@code{nil}, only output from that process is handled, suspending output
1481from other processes until some output has been received from that
1482process or the timeout expires. If @var{just-this-one} is an integer,
1483also inhibit running timers. This feature is generally not
1484recommended, but may be necessary for specific applications, such as
1485speech synthesis.
1486
1487The function @code{accept-process-output} returns non-@code{nil} if it
1488did get some output, or @code{nil} if the timeout expired before output
1489arrived.
1490@end defun
1491
1492@node Sentinels
1493@section Sentinels: Detecting Process Status Changes
1494@cindex process sentinel
1495@cindex sentinel (of process)
1496
1497 A @dfn{process sentinel} is a function that is called whenever the
1498associated process changes status for any reason, including signals
1499(whether sent by Emacs or caused by the process's own actions) that
1500terminate, stop, or continue the process. The process sentinel is
1501also called if the process exits. The sentinel receives two
1502arguments: the process for which the event occurred, and a string
1503describing the type of event.
1504
1505 The string describing the event looks like one of the following:
1506
1507@itemize @bullet
1508@item
1509@code{"finished\n"}.
1510
1511@item
1512@code{"exited abnormally with code @var{exitcode}\n"}.
1513
1514@item
1515@code{"@var{name-of-signal}\n"}.
1516
1517@item
1518@code{"@var{name-of-signal} (core dumped)\n"}.
1519@end itemize
1520
1521 A sentinel runs only while Emacs is waiting (e.g., for terminal
1522input, or for time to elapse, or for process output). This avoids the
1523timing errors that could result from running them at random places in
1524the middle of other Lisp programs. A program can wait, so that
1525sentinels will run, by calling @code{sit-for} or @code{sleep-for}
1526(@pxref{Waiting}), or @code{accept-process-output} (@pxref{Accepting
1527Output}). Emacs also allows sentinels to run when the command loop is
1528reading input. @code{delete-process} calls the sentinel when it
1529terminates a running process.
1530
1531 Emacs does not keep a queue of multiple reasons to call the sentinel
1532of one process; it records just the current status and the fact that
1533there has been a change. Therefore two changes in status, coming in
1534quick succession, can call the sentinel just once. However, process
1535termination will always run the sentinel exactly once. This is
1536because the process status can't change again after termination.
1537
1538 Emacs explicitly checks for output from the process before running
1539the process sentinel. Once the sentinel runs due to process
1540termination, no further output can arrive from the process.
1541
1542 A sentinel that writes the output into the buffer of the process
1543should check whether the buffer is still alive. If it tries to insert
1544into a dead buffer, it will get an error. If the buffer is dead,
1545@code{(buffer-name (process-buffer @var{process}))} returns @code{nil}.
1546
1547 Quitting is normally inhibited within a sentinel---otherwise, the
1548effect of typing @kbd{C-g} at command level or to quit a user command
1549would be unpredictable. If you want to permit quitting inside a
1550sentinel, bind @code{inhibit-quit} to @code{nil}. In most cases, the
1551right way to do this is with the macro @code{with-local-quit}.
1552@xref{Quitting}.
1553
1554 If an error happens during execution of a sentinel, it is caught
1555automatically, so that it doesn't stop the execution of whatever
1556programs was running when the sentinel was started. However, if
1557@code{debug-on-error} is non-@code{nil}, the error-catching is turned
1558off. This makes it possible to use the Lisp debugger to debug the
1559sentinel. @xref{Debugger}.
1560
1561 While a sentinel is running, the process sentinel is temporarily
1562set to @code{nil} so that the sentinel won't run recursively.
1563For this reason it is not possible for a sentinel to specify
1564a new sentinel.
1565
1566 In earlier Emacs versions, every sentinel that did regular expression
1567searching or matching had to explicitly save and restore the match data.
1568Now Emacs does this automatically for sentinels; they never need to do
1569it explicitly. @xref{Match Data}.
1570
1571@defun set-process-sentinel process sentinel
1572This function associates @var{sentinel} with @var{process}. If
1573@var{sentinel} is @code{nil}, then the process will have no sentinel.
1574The default behavior when there is no sentinel is to insert a message in
1575the process's buffer when the process status changes.
1576
1577Changes in process sentinel take effect immediately---if the sentinel
1578is slated to be run but has not been called yet, and you specify a new
1579sentinel, the eventual call to the sentinel will use the new one.
1580
1581@smallexample
1582@group
1583(defun msg-me (process event)
1584 (princ
1585 (format "Process: %s had the event `%s'" process event)))
1586(set-process-sentinel (get-process "shell") 'msg-me)
1587 @result{} msg-me
1588@end group
1589@group
1590(kill-process (get-process "shell"))
1591 @print{} Process: #<process shell> had the event `killed'
1592 @result{} #<process shell>
1593@end group
1594@end smallexample
1595@end defun
1596
1597@defun process-sentinel process
1598This function returns the sentinel of @var{process}, or @code{nil} if it
1599has none.
1600@end defun
1601
1602@defun waiting-for-user-input-p
1603While a sentinel or filter function is running, this function returns
1604non-@code{nil} if Emacs was waiting for keyboard input from the user at
1605the time the sentinel or filter function was called, @code{nil} if it
1606was not.
1607@end defun
1608
1609@node Query Before Exit
1610@section Querying Before Exit
1611
1612 When Emacs exits, it terminates all its subprocesses by sending them
1613the @code{SIGHUP} signal. Because subprocesses may be doing
1614valuable work, Emacs normally asks the user to confirm that it is ok
1615to terminate them. Each process has a query flag which, if
1616non-@code{nil}, says that Emacs should ask for confirmation before
1617exiting and thus killing that process. The default for the query flag
1618is @code{t}, meaning @emph{do} query.
1619
1620@defun process-query-on-exit-flag process
1621This returns the query flag of @var{process}.
1622@end defun
1623
1624@defun set-process-query-on-exit-flag process flag
1625This function sets the query flag of @var{process} to @var{flag}. It
1626returns @var{flag}.
1627
1628@smallexample
1629@group
1630;; @r{Don't query about the shell process}
1631(set-process-query-on-exit-flag (get-process "shell") nil)
1632 @result{} t
1633@end group
1634@end smallexample
1635@end defun
1636
1637@defun process-kill-without-query process &optional do-query
1638This function clears the query flag of @var{process}, so that
1639Emacs will not query the user on account of that process.
1640
1641Actually, the function does more than that: it returns the old value of
1642the process's query flag, and sets the query flag to @var{do-query}.
1643Please don't use this function to do those things any more---please
1644use the newer, cleaner functions @code{process-query-on-exit-flag} and
1645@code{set-process-query-on-exit-flag} in all but the simplest cases.
1646The only way you should use @code{process-kill-without-query} nowadays
1647is like this:
1648
1649@smallexample
1650@group
1651;; @r{Don't query about the shell process}
1652(process-kill-without-query (get-process "shell"))
1653@end group
1654@end smallexample
1655@end defun
1656
23dd4ecd
EZ
1657@node System Processes
1658@section Accessing Other Processes
1659@cindex system processes
1660
1661 In addition to accessing and manipulating processes that are
1662subprocesses of the current Emacs session, Emacs Lisp programs can
1663also access other processes running on the same machine. We call
1664these @dfn{system processes}, to distinguish between them and Emacs
1665subprocesses.
1666
1667 Emacs provides several primitives for accessing system processes.
1668Not all platforms support these primitives; on those which don't,
1669these primitives return @code{nil}.
1670
1671@defun list-system-processes
1672This function returns a list of all the processes running on the
1673system. Each process is identified by its @acronym{PID}, a numerical
1674process ID that is assigned by the OS and distinguishes the process
1675from all the other processes running on the same machine at the same
1676time.
1677@end defun
1678
a20878b6 1679@defun process-attributes pid
23dd4ecd
EZ
1680This function returns an alist of attributes for the process specified
1681by its process ID @var{pid}. Each association in the alist is of the
1682form @code{(@var{key} . @var{value})}, where @var{key} designates the
1683attribute and @var{value} is the value of that attribute. The various
1684attribute @var{key}'s that this function can return are listed below.
1685Not all platforms support all of these attributes; if an attribute is
1686not supported, its association will not appear in the returned alist.
1687Values that are numbers can be either integer or floating-point,
1688depending on the magnitude of the value.
1689
1690@table @code
1691@item euid
1692The effective user ID of the user who invoked the process. The
1693corresponding @var{value} is a number. If the process was invoked by
1694the same user who runs the current Emacs session, the value is
1695identical to what @code{user-uid} returns (@pxref{User
1696Identification}).
1697
1698@item user
1699User name corresponding to the process's effective user ID, a string.
1700
1701@item egid
1702The group ID of the effective user ID, a number.
1703
1704@item group
1705Group name corresponding to the effective user's group ID, a string.
1706
1707@item comm
1708The name of the command that runs in the process. This is a string
1709that usually specifies the name of the executable file of the process,
1710without the leading directories. However, some special system
1711processes can report strings that do not correspond to an executable
1712file of a program.
1713
1714@item state
1715The state code of the process. This is a short string that encodes
1716the scheduling state of the process. Here's a list of the most
1717frequently seen codes:
1718
1719@table @code
1dca458f 1720@item "D"
23dd4ecd 1721uninterruptible sleep (usually I/O)
1dca458f 1722@item "R"
23dd4ecd 1723running
1dca458f 1724@item "S"
23dd4ecd 1725interruptible sleep (waiting for some event)
1dca458f 1726@item "T"
23dd4ecd 1727stopped, e.g., by a job control signal
1dca458f
EZ
1728@item "Z"
1729``zombie'': a process that terminated, but was not reaped by its parent
23dd4ecd
EZ
1730@end table
1731
1732@noindent
1733For the full list of the possible states, see the manual page of the
1734@command{ps} command.
1735
1736@item ppid
1737The process ID of the parent process, a number.
1738
1739@item pgrp
1740The process group ID of the process, a number.
1741
1742@item sess
1743The session ID of the process. This is a number that is the process
1744ID of the process's @dfn{session leader}.
1745
1746@item ttname
1747A string that is the name of the process's controlling terminal. On
1748Unix and GNU systems, this is normally the file name of the
1749corresponding terminal device, such as @file{/dev/pts65}.
1750
1751@item tpgid
1752The numerical process group ID of the foreground process group that
1753uses the process's terminal.
1754
1755@item minflt
1756The number of minor page faults caused by the process since its
1757beginning. (Minor page faults are those that don't involve reading
1758from disk.)
1759
1760@item majflt
1761The number of major page faults caused by the process since its
1762beginning. (Major page faults require a disk to be read, and are thus
1763more expensive than minor page faults.)
1764
1765@item cminflt
1766@itemx cmajflt
1767Like @code{minflt} and @code{majflt}, but include the number of page
1768faults for all the child processes of the given process.
1769
1770@item utime
1771Time spent by the process in the user context, for running the
1772application's code. The corresponding @var{value} is in the
1773@w{@code{(@var{high} @var{low} @var{microsec})}} format, the same
1774format used by functions @code{current-time} (@pxref{Time of Day,
1775current-time}) and @code{file-attributes} (@pxref{File Attributes}).
1776
1777@item stime
1778Time spent by the process in the system (kernel) context, for
1779processing system calls. The corresponding @var{value} is in the same
1780format as for @code{utime}.
1781
af34ad36
EZ
1782@item time
1783The sum of @code{utime} and @code{stime}. The corresponding
1784@var{value} is in the same format as for @code{utime}.
1785
23dd4ecd
EZ
1786@item cutime
1787@itemx cstime
af34ad36
EZ
1788@itemx ctime
1789Like @code{utime}, @code{stime}, and @code{time}, but include the
1790times of all the child processes of the given process.
23dd4ecd
EZ
1791
1792@item pri
1793The numerical priority of the process.
1794
1795@item nice
1dca458f
EZ
1796The @dfn{nice value} of the process, a number. (Processes with smaller
1797nice values get scheduled more favorably.)
23dd4ecd
EZ
1798
1799@item thcount
1800The number of threads in the process.
1801
1802@item start
049bcbcb
CY
1803The time when the process was started, in the same
1804@w{@code{(@var{high} @var{low} @var{microsec})}} format used by
1805@code{current-time} and @code{file-attributes}.
23dd4ecd
EZ
1806
1807@item etime
1808The time elapsed since the process started, in the @w{@code{(@var{high}
1809@var{low} @var{microsec})}} format.
1810
1811@item vsize
1812The virtual memory size of the process, measured in kilobytes.
1813
1814@item rss
1815The size of the process's @dfn{resident set}, the number of kilobytes
1816occupied by the process in the machine's physical memory.
1817
1818@item pcpu
1819The percentage of the CPU time used by the process since it started.
1820The corresponding @var{value} is a floating-point number between 0 and
1821100.
1822
1823@item pmem
1824The percentage of the total physical memory installed on the machine
1825used by the process's resident set. The value is a floating-point
1826number between 0 and 100.
1827
1828@item args
1829The command-line with which the process was invoked. This is a string
1830in which individual command-line arguments are separated by blanks;
1831whitespace characters that are embedded in the arguments are quoted as
1832appropriate for the system's shell: escaped by backslash characters on
1833GNU and Unix, and enclosed in double quote characters on Windows.
1834Thus, this command-line string can be directly used in primitives such
1835as @code{shell-command}.
1836@end table
1837
1838@end defun
1839
1840
b8d4c8d0
GM
1841@node Transaction Queues
1842@section Transaction Queues
1843@cindex transaction queue
1844
1845You can use a @dfn{transaction queue} to communicate with a subprocess
1846using transactions. First use @code{tq-create} to create a transaction
1847queue communicating with a specified process. Then you can call
1848@code{tq-enqueue} to send a transaction.
1849
1850@defun tq-create process
1851This function creates and returns a transaction queue communicating with
1852@var{process}. The argument @var{process} should be a subprocess
1853capable of sending and receiving streams of bytes. It may be a child
1854process, or it may be a TCP connection to a server, possibly on another
1855machine.
1856@end defun
1857
1858@defun tq-enqueue queue question regexp closure fn &optional delay-question
1859This function sends a transaction to queue @var{queue}. Specifying the
1860queue has the effect of specifying the subprocess to talk to.
1861
1862The argument @var{question} is the outgoing message that starts the
1863transaction. The argument @var{fn} is the function to call when the
1864corresponding answer comes back; it is called with two arguments:
1865@var{closure}, and the answer received.
1866
1867The argument @var{regexp} is a regular expression that should match
1868text at the end of the entire answer, but nothing before; that's how
1869@code{tq-enqueue} determines where the answer ends.
1870
4185820c
CY
1871If the argument @var{delay-question} is non-@code{nil}, delay sending
1872this question until the process has finished replying to any previous
b8d4c8d0
GM
1873questions. This produces more reliable results with some processes.
1874
1875The return value of @code{tq-enqueue} itself is not meaningful.
1876@end defun
1877
1878@defun tq-close queue
1879Shut down transaction queue @var{queue}, waiting for all pending transactions
1880to complete, and then terminate the connection or child process.
1881@end defun
1882
1883Transaction queues are implemented by means of a filter function.
1884@xref{Filter Functions}.
1885
1886@node Network
1887@section Network Connections
1888@cindex network connection
1889@cindex TCP
1890@cindex UDP
1891
1892 Emacs Lisp programs can open stream (TCP) and datagram (UDP) network
1893connections to other processes on the same machine or other machines.
1894A network connection is handled by Lisp much like a subprocess, and is
1895represented by a process object. However, the process you are
1896communicating with is not a child of the Emacs process, so it has no
1897process @acronym{ID}, and you can't kill it or send it signals. All you
1898can do is send and receive data. @code{delete-process} closes the
1899connection, but does not kill the program at the other end; that
1900program must decide what to do about closure of the connection.
1901
1902 Lisp programs can listen for connections by creating network
1903servers. A network server is also represented by a kind of process
1904object, but unlike a network connection, the network server never
1905transfers data itself. When it receives a connection request, it
1906creates a new network connection to represent the connection just
1907made. (The network connection inherits certain information, including
1908the process plist, from the server.) The network server then goes
1909back to listening for more connection requests.
1910
1911 Network connections and servers are created by calling
1912@code{make-network-process} with an argument list consisting of
1913keyword/argument pairs, for example @code{:server t} to create a
1914server process, or @code{:type 'datagram} to create a datagram
1915connection. @xref{Low-Level Network}, for details. You can also use
1916the @code{open-network-stream} function described below.
1917
c73e02fa
GM
1918 To distinguish the different types of processes, the
1919@code{process-type} function returns the symbol @code{network} for a
1920network connection or server, @code{serial} for a serial port
1921connection, or @code{real} for a real subprocess.
1922
1923 The @code{process-status} function returns @code{open},
1924@code{closed}, @code{connect}, and @code{failed} for network
1925connections. For a network server, the status is always
b8d4c8d0
GM
1926@code{listen}. None of those values is possible for a real
1927subprocess. @xref{Process Information}.
1928
1929 You can stop and resume operation of a network process by calling
1930@code{stop-process} and @code{continue-process}. For a server
1931process, being stopped means not accepting new connections. (Up to 5
1932connection requests will be queued for when you resume the server; you
1933can increase this limit, unless it is imposed by the operating
1934system.) For a network stream connection, being stopped means not
1935processing input (any arriving input waits until you resume the
1936connection). For a datagram connection, some number of packets may be
1937queued but input may be lost. You can use the function
1938@code{process-command} to determine whether a network connection or
1939server is stopped; a non-@code{nil} value means yes.
1940
1941@defun open-network-stream name buffer-or-name host service
1942This function opens a TCP connection, and returns a process object
1943that represents the connection.
1944
1945The @var{name} argument specifies the name for the process object. It
1946is modified as necessary to make it unique.
1947
1948The @var{buffer-or-name} argument is the buffer to associate with the
1949connection. Output from the connection is inserted in the buffer,
1950unless you specify a filter function to handle the output. If
1951@var{buffer-or-name} is @code{nil}, it means that the connection is not
1952associated with any buffer.
1953
1954The arguments @var{host} and @var{service} specify where to connect to;
1955@var{host} is the host name (a string), and @var{service} is the name of
1956a defined network service (a string) or a port number (an integer).
1957@end defun
1958
b8d4c8d0
GM
1959@node Network Servers
1960@section Network Servers
1961@cindex network servers
1962
1963 You create a server by calling @code{make-network-process} with
1964@code{:server t}. The server will listen for connection requests from
1965clients. When it accepts a client connection request, that creates a
1966new network connection, itself a process object, with the following
1967parameters:
1968
1969@itemize @bullet
1970@item
1971The connection's process name is constructed by concatenating the
1972server process' @var{name} with a client identification string. The
1973client identification string for an IPv4 connection looks like
1974@samp{<@var{a}.@var{b}.@var{c}.@var{d}:@var{p}>}. Otherwise, it is a
1975unique number in brackets, as in @samp{<@var{nnn}>}. The number
1976is unique for each connection in the Emacs session.
1977
1978@item
1979If the server's filter is non-@code{nil}, the connection process does
1980not get a separate process buffer; otherwise, Emacs creates a new
1981buffer for the purpose. The buffer name is the server's buffer name
1982or process name, concatenated with the client identification string.
1983
cec2eab8
JB
1984The server's process buffer value is never used directly, but the log
1985function can retrieve it and use it to log connections by inserting
1986text there.
b8d4c8d0
GM
1987
1988@item
1989The communication type and the process filter and sentinel are
1990inherited from those of the server. The server never directly
1991uses its filter and sentinel; their sole purpose is to initialize
1992connections made to the server.
1993
1994@item
1995The connection's process contact info is set according to the client's
1996addressing information (typically an IP address and a port number).
1997This information is associated with the @code{process-contact}
1998keywords @code{:host}, @code{:service}, @code{:remote}.
1999
2000@item
2001The connection's local address is set up according to the port
2002number used for the connection.
2003
2004@item
2005The client process' plist is initialized from the server's plist.
2006@end itemize
2007
2008@node Datagrams
2009@section Datagrams
2010@cindex datagrams
2011
2012 A datagram connection communicates with individual packets rather
2013than streams of data. Each call to @code{process-send} sends one
2014datagram packet (@pxref{Input to Processes}), and each datagram
2015received results in one call to the filter function.
2016
2017 The datagram connection doesn't have to talk with the same remote
2018peer all the time. It has a @dfn{remote peer address} which specifies
2019where to send datagrams to. Each time an incoming datagram is passed
2020to the filter function, the peer address is set to the address that
2021datagram came from; that way, if the filter function sends a datagram,
2022it will go back to that place. You can specify the remote peer
2023address when you create the datagram connection using the
2024@code{:remote} keyword. You can change it later on by calling
2025@code{set-process-datagram-address}.
2026
2027@defun process-datagram-address process
2028If @var{process} is a datagram connection or server, this function
2029returns its remote peer address.
2030@end defun
2031
2032@defun set-process-datagram-address process address
2033If @var{process} is a datagram connection or server, this function
2034sets its remote peer address to @var{address}.
2035@end defun
2036
2037@node Low-Level Network
2038@section Low-Level Network Access
2039
2040 You can also create network connections by operating at a lower
2041level than that of @code{open-network-stream}, using
2042@code{make-network-process}.
2043
2044@menu
2045* Proc: Network Processes. Using @code{make-network-process}.
2046* Options: Network Options. Further control over network connections.
2047* Features: Network Feature Testing.
2048 Determining which network features work on
2049 the machine you are using.
2050@end menu
2051
2052@node Network Processes
2053@subsection @code{make-network-process}
2054
2055 The basic function for creating network connections and network
2056servers is @code{make-network-process}. It can do either of those
2057jobs, depending on the arguments you give it.
2058
2059@defun make-network-process &rest args
2060This function creates a network connection or server and returns the
2061process object that represents it. The arguments @var{args} are a
2062list of keyword/argument pairs. Omitting a keyword is always
2063equivalent to specifying it with value @code{nil}, except for
2064@code{:coding}, @code{:filter-multibyte}, and @code{:reuseaddr}. Here
2065are the meaningful keywords:
2066
2067@table @asis
2068@item :name @var{name}
2069Use the string @var{name} as the process name. It is modified if
2070necessary to make it unique.
2071
2072@item :type @var{type}
2073Specify the communication type. A value of @code{nil} specifies a
2074stream connection (the default); @code{datagram} specifies a datagram
f7704e26
CY
2075connection; @code{seqpacket} specifies a ``sequenced packet stream''
2076connection. Both connections and servers can be of these types.
b8d4c8d0
GM
2077
2078@item :server @var{server-flag}
2079If @var{server-flag} is non-@code{nil}, create a server. Otherwise,
2080create a connection. For a stream type server, @var{server-flag} may
2081be an integer which then specifies the length of the queue of pending
2082connections to the server. The default queue length is 5.
2083
2084@item :host @var{host}
2085Specify the host to connect to. @var{host} should be a host name or
2086Internet address, as a string, or the symbol @code{local} to specify
2087the local host. If you specify @var{host} for a server, it must
2088specify a valid address for the local host, and only clients
2089connecting to that address will be accepted.
2090
2091@item :service @var{service}
2092@var{service} specifies a port number to connect to, or, for a server,
2093the port number to listen on. It should be a service name that
2094translates to a port number, or an integer specifying the port number
2095directly. For a server, it can also be @code{t}, which means to let
2096the system select an unused port number.
2097
2098@item :family @var{family}
2099@var{family} specifies the address (and protocol) family for
2100communication. @code{nil} means determine the proper address family
2101automatically for the given @var{host} and @var{service}.
2102@code{local} specifies a Unix socket, in which case @var{host} is
2103ignored. @code{ipv4} and @code{ipv6} specify to use IPv4 and IPv6
2104respectively.
2105
2106@item :local @var{local-address}
2107For a server process, @var{local-address} is the address to listen on.
2108It overrides @var{family}, @var{host} and @var{service}, and you
2109may as well not specify them.
2110
2111@item :remote @var{remote-address}
2112For a connection, @var{remote-address} is the address to connect to.
2113It overrides @var{family}, @var{host} and @var{service}, and you
2114may as well not specify them.
2115
2116For a datagram server, @var{remote-address} specifies the initial
2117setting of the remote datagram address.
2118
2119The format of @var{local-address} or @var{remote-address} depends on
2120the address family:
2121
2122@itemize -
2123@item
2124An IPv4 address is represented as a five-element vector of four 8-bit
2125integers and one 16-bit integer
2126@code{[@var{a} @var{b} @var{c} @var{d} @var{p}]} corresponding to
2127numeric IPv4 address @var{a}.@var{b}.@var{c}.@var{d} and port number
2128@var{p}.
2129
2130@item
2131An IPv6 address is represented as a nine-element vector of 16-bit
2132integers @code{[@var{a} @var{b} @var{c} @var{d} @var{e} @var{f}
2133@var{g} @var{h} @var{p}]} corresponding to numeric IPv6 address
2134@var{a}:@var{b}:@var{c}:@var{d}:@var{e}:@var{f}:@var{g}:@var{h} and
2135port number @var{p}.
2136
2137@item
2138A local address is represented as a string which specifies the address
2139in the local address space.
2140
2141@item
2142An ``unsupported family'' address is represented by a cons
2143@code{(@var{f} . @var{av})}, where @var{f} is the family number and
2144@var{av} is a vector specifying the socket address using one element
2145per address data byte. Do not rely on this format in portable code,
2146as it may depend on implementation defined constants, data sizes, and
2147data structure alignment.
2148@end itemize
2149
2150@item :nowait @var{bool}
2151If @var{bool} is non-@code{nil} for a stream connection, return
2152without waiting for the connection to complete. When the connection
2153succeeds or fails, Emacs will call the sentinel function, with a
2154second argument matching @code{"open"} (if successful) or
2155@code{"failed"}. The default is to block, so that
2156@code{make-network-process} does not return until the connection
2157has succeeded or failed.
2158
2159@item :stop @var{stopped}
2160Start the network connection or server in the `stopped' state if
2161@var{stopped} is non-@code{nil}.
2162
2163@item :buffer @var{buffer}
2164Use @var{buffer} as the process buffer.
2165
2166@item :coding @var{coding}
2167Use @var{coding} as the coding system for this process. To specify
2168different coding systems for decoding data from the connection and for
2169encoding data sent to it, specify @code{(@var{decoding} .
2170@var{encoding})} for @var{coding}.
2171
2172If you don't specify this keyword at all, the default
2173is to determine the coding systems from the data.
2174
2175@item :noquery @var{query-flag}
2176Initialize the process query flag to @var{query-flag}.
2177@xref{Query Before Exit}.
2178
2179@item :filter @var{filter}
2180Initialize the process filter to @var{filter}.
2181
b8d4c8d0
GM
2182@item :sentinel @var{sentinel}
2183Initialize the process sentinel to @var{sentinel}.
2184
2185@item :log @var{log}
2186Initialize the log function of a server process to @var{log}. The log
2187function is called each time the server accepts a network connection
2188from a client. The arguments passed to the log function are
2189@var{server}, @var{connection}, and @var{message}, where @var{server}
2190is the server process, @var{connection} is the new process for the
2191connection, and @var{message} is a string describing what has
2192happened.
2193
2194@item :plist @var{plist}
2195Initialize the process plist to @var{plist}.
2196@end table
2197
2198The original argument list, modified with the actual connection
2199information, is available via the @code{process-contact} function.
2200@end defun
2201
2202@node Network Options
2203@subsection Network Options
2204
2205 The following network options can be specified when you create a
2206network process. Except for @code{:reuseaddr}, you can also set or
2207modify these options later, using @code{set-network-process-option}.
2208
2209 For a server process, the options specified with
2210@code{make-network-process} are not inherited by the client
2211connections, so you will need to set the necessary options for each
2212child connection as it is created.
2213
2214@table @asis
2215@item :bindtodevice @var{device-name}
2216If @var{device-name} is a non-empty string identifying a network
2217interface name (see @code{network-interface-list}), only handle
2218packets received on that interface. If @var{device-name} is @code{nil}
2219(the default), handle packets received on any interface.
2220
2221Using this option may require special privileges on some systems.
2222
2223@item :broadcast @var{broadcast-flag}
2224If @var{broadcast-flag} is non-@code{nil} for a datagram process, the
2225process will receive datagram packet sent to a broadcast address, and
2226be able to send packets to a broadcast address. Ignored for a stream
2227connection.
2228
2229@item :dontroute @var{dontroute-flag}
2230If @var{dontroute-flag} is non-@code{nil}, the process can only send
2231to hosts on the same network as the local host.
2232
2233@item :keepalive @var{keepalive-flag}
2234If @var{keepalive-flag} is non-@code{nil} for a stream connection,
2235enable exchange of low-level keep-alive messages.
2236
2237@item :linger @var{linger-arg}
2238If @var{linger-arg} is non-@code{nil}, wait for successful
2239transmission of all queued packets on the connection before it is
2240deleted (see @code{delete-process}). If @var{linger-arg} is an
2241integer, it specifies the maximum time in seconds to wait for queued
2242packets to be sent before closing the connection. Default is
2243@code{nil} which means to discard unsent queued packets when the
2244process is deleted.
2245
2246@item :oobinline @var{oobinline-flag}
2247If @var{oobinline-flag} is non-@code{nil} for a stream connection,
2248receive out-of-band data in the normal data stream. Otherwise, ignore
2249out-of-band data.
2250
2251@item :priority @var{priority}
2252Set the priority for packets sent on this connection to the integer
2253@var{priority}. The interpretation of this number is protocol
2254specific, such as setting the TOS (type of service) field on IP
2255packets sent on this connection. It may also have system dependent
2256effects, such as selecting a specific output queue on the network
2257interface.
2258
2259@item :reuseaddr @var{reuseaddr-flag}
2260If @var{reuseaddr-flag} is non-@code{nil} (the default) for a stream
2261server process, allow this server to reuse a specific port number (see
2262@code{:service}) unless another process on this host is already
2263listening on that port. If @var{reuseaddr-flag} is @code{nil}, there
2264may be a period of time after the last use of that port (by any
2265process on the host), where it is not possible to make a new server on
2266that port.
2267@end table
2268
106e6894 2269@defun set-network-process-option process option value &optional no-error
b8d4c8d0
GM
2270This function sets or modifies a network option for network process
2271@var{process}. See @code{make-network-process} for details of options
106e6894
CY
2272@var{option} and their corresponding values @var{value}. If
2273@var{no-error} is non-@code{nil}, this function returns @code{nil}
2274instead of signaling an error if @var{option} is not a supported
2275option. If the function successfully completes, it returns @code{t}.
b8d4c8d0
GM
2276
2277The current setting of an option is available via the
2278@code{process-contact} function.
2279@end defun
2280
2281@node Network Feature Testing
2282@subsection Testing Availability of Network Features
2283
2284 To test for the availability of a given network feature, use
2285@code{featurep} like this:
2286
2287@example
2288(featurep 'make-network-process '(@var{keyword} @var{value}))
2289@end example
2290
2291@noindent
2292The result of the first form is @code{t} if it works to specify
2293@var{keyword} with value @var{value} in @code{make-network-process}.
2294The result of the second form is @code{t} if @var{keyword} is
2295supported by @code{make-network-process}. Here are some of the
2296@var{keyword}---@var{value} pairs you can test in
2297this way.
2298
2299@table @code
2300@item (:nowait t)
2301Non-@code{nil} if non-blocking connect is supported.
2302@item (:type datagram)
2303Non-@code{nil} if datagrams are supported.
2304@item (:family local)
2305Non-@code{nil} if local (a.k.a.@: ``UNIX domain'') sockets are supported.
2306@item (:family ipv6)
2307Non-@code{nil} if IPv6 is supported.
2308@item (:service t)
2309Non-@code{nil} if the system can select the port for a server.
2310@end table
2311
2312 To test for the availability of a given network option, use
2313@code{featurep} like this:
2314
2315@example
2316(featurep 'make-network-process '@var{keyword})
2317@end example
2318
2319@noindent
2320Here are some of the options you can test in this way.
2321
2322@table @code
2323@item :bindtodevice
2324@itemx :broadcast
2325@itemx :dontroute
2326@itemx :keepalive
2327@itemx :linger
2328@itemx :oobinline
2329@itemx :priority
2330@itemx :reuseaddr
2331That particular network option is supported by
2332@code{make-network-process} and @code{set-network-process-option}.
2333@end table
2334
2335@node Misc Network
2336@section Misc Network Facilities
2337
2338 These additional functions are useful for creating and operating
305a7ef2
EZ
2339on network connections. Note that they are supported only on some
2340systems.
b8d4c8d0
GM
2341
2342@defun network-interface-list
2343This function returns a list describing the network interfaces
2344of the machine you are using. The value is an alist whose
2345elements have the form @code{(@var{name} . @var{address})}.
2346@var{address} has the same form as the @var{local-address}
2347and @var{remote-address} arguments to @code{make-network-process}.
2348@end defun
2349
2350@defun network-interface-info ifname
2351This function returns information about the network interface named
2352@var{ifname}. The value is a list of the form
2353@code{(@var{addr} @var{bcast} @var{netmask} @var{hwaddr} @var{flags})}.
2354
2355@table @var
2356@item addr
2357The Internet protocol address.
2358@item bcast
2359The broadcast address.
2360@item netmask
2361The network mask.
2362@item hwaddr
2363The layer 2 address (Ethernet MAC address, for instance).
2364@item flags
2365The current flags of the interface.
2366@end table
2367@end defun
2368
2369@defun format-network-address address &optional omit-port
2370This function converts the Lisp representation of a network address to
2371a string.
2372
2373A five-element vector @code{[@var{a} @var{b} @var{c} @var{d} @var{p}]}
2374represents an IPv4 address @var{a}.@var{b}.@var{c}.@var{d} and port
2375number @var{p}. @code{format-network-address} converts that to the
2376string @code{"@var{a}.@var{b}.@var{c}.@var{d}:@var{p}"}.
2377
2378A nine-element vector @code{[@var{a} @var{b} @var{c} @var{d} @var{e}
2379@var{f} @var{g} @var{h} @var{p}]} represents an IPv6 address along
2380with a port number. @code{format-network-address} converts that to
2381the string
2382@code{"[@var{a}:@var{b}:@var{c}:@var{d}:@var{e}:@var{f}:@var{g}:@var{h}]:@var{p}"}.
2383
2384If the vector does not include the port number, @var{p}, or if
2385@var{omit-port} is non-@code{nil}, the result does not include the
2386@code{:@var{p}} suffix.
2387@end defun
2388
c73e02fa
GM
2389@node Serial Ports
2390@section Communicating with Serial Ports
2391@cindex @file{/dev/tty}
2392@cindex @file{COM1}
545c2782 2393@cindex serial connections
c73e02fa
GM
2394
2395 Emacs can communicate with serial ports. For interactive use,
2396@kbd{M-x serial-term} opens a terminal window. In a Lisp program,
2397@code{make-serial-process} creates a process object.
2398
2399 The serial port can be configured at run-time, without having to
2400close and re-open it. The function @code{serial-process-configure}
2401lets you change the speed, bytesize, and other parameters. In a
2402terminal window created by @code{serial-term}, you can click on the
2403mode line for configuration.
2404
2405 A serial connection is represented by a process object which can be
2406used similar to a subprocess or network process. You can send and
2407receive data and configure the serial port. A serial process object
80e6b6df
EZ
2408has no process ID, you can't send signals to it, and the status codes
2409are different from other types of processes.
c73e02fa
GM
2410@code{delete-process} on the process object or @code{kill-buffer} on
2411the process buffer close the connection, but this does not affect the
2412device connected to the serial port.
2413
2414 The function @code{process-type} returns the symbol @code{serial}
80e6b6df 2415for a process object representing a serial port connection.
c73e02fa
GM
2416
2417 Serial ports are available on GNU/Linux, Unix, and Windows systems.
2418
80e6b6df 2419@deffn Command serial-term port speed
c73e02fa 2420Start a terminal-emulator for a serial port in a new buffer.
80e6b6df
EZ
2421@var{port} is the name of the serial port to which to connect. For
2422example, this could be @file{/dev/ttyS0} on Unix. On Windows, this
2423could be @file{COM1}, or @file{\\.\COM10} (double the backslashes in
2424Lisp strings).
c73e02fa
GM
2425
2426@var{speed} is the speed of the serial port in bits per second. 9600
80e6b6df
EZ
2427is a common value. The buffer is in Term mode; see @ref{Term Mode,,,
2428emacs, The GNU Emacs Manual}, for the commands to use in that buffer.
2429You can change the speed and the configuration in the mode line menu.
2430@end deffn
c73e02fa
GM
2431
2432@defun make-serial-process &rest args
80e6b6df
EZ
2433This function creates a process and a buffer. Arguments are specified
2434as keyword/argument pairs. Here's the list of the meaningful keywords:
c73e02fa
GM
2435
2436@table @code
80e6b6df
EZ
2437@item :port @var{port}@r{ (mandatory)}
2438This is the name of the serial port. On Unix and GNU systems, this is
2439a file name such as @file{/dev/ttyS0}. On Windows, this could be
2440@file{COM1}, or @file{\\.\COM10} for ports higher than @file{COM9}
2441(double the backslashes in Lisp strings).
2442
2443@item :speed @var{speed}@r{ (mandatory)}
2444The speed of the serial port in bits per second. This function calls
2445@code{serial-process-configure} to handle the speed.
2446
2447@item :name @var{name}
2448The name of the process. If @var{name} is not given, @var{port} will
2449serve as the process name as well.
2450
2451@item :buffer @var{buffer}
2452The buffer to associate with the process. The value could be either a
2453buffer or a string that names a buffer. Process output goes at the
2454end of that buffer, unless you specify an output stream or filter
2455function to handle the output. If @var{buffer} is not given, the
2456process buffer's name is taken from the value of the @code{:name}
2457keyword.
2458
2459@item :coding @var{coding}
c73e02fa
GM
2460If @var{coding} is a symbol, it specifies the coding system used for
2461both reading and writing for this process. If @var{coding} is a cons
2462@code{(decoding . encoding)}, @var{decoding} is used for reading, and
80e6b6df
EZ
2463@var{encoding} is used for writing. If not specified, the default is
2464to determine the coding systems from data itself.
c73e02fa 2465
80e6b6df
EZ
2466@item :noquery @var{query-flag}
2467Initialize the process query flag to @var{query-flag}. @xref{Query
2468Before Exit}. The flags defaults to @code{nil} if unspecified.
c73e02fa 2469
80e6b6df 2470@item :stop @var{bool}
c73e02fa
GM
2471Start process in the @code{stopped} state if @var{bool} is
2472non-@code{nil}. In the stopped state, a serial process does not
2473accept incoming data, but you can send outgoing data. The stopped
2474state is cleared by @code{continue-process} and set by
2475@code{stop-process}.
2476
80e6b6df 2477@item :filter @var{filter}
c73e02fa
GM
2478Install @var{filter} as the process filter.
2479
80e6b6df 2480@item :sentinel @var{sentinel}
c73e02fa
GM
2481Install @var{sentinel} as the process sentinel.
2482
80e6b6df 2483@item :plist @var{plist}
c73e02fa
GM
2484Install @var{plist} as the initial plist of the process.
2485
2486@item :speed
2487@itemx :bytesize
2488@itemx :parity
2489@itemx :stopbits
2490@itemx :flowcontrol
049bcbcb
CY
2491These are handled by @code{serial-process-configure}, which is called
2492by @code{make-serial-process}.
c73e02fa
GM
2493@end table
2494
2495The original argument list, possibly modified by later configuration,
2496is available via the function @code{process-contact}.
2497
049bcbcb 2498Here is an example:
c73e02fa
GM
2499
2500@example
2501(make-serial-process :port "/dev/ttyS0" :speed 9600)
c73e02fa
GM
2502@end example
2503@end defun
2504
2505@defun serial-process-configure &rest args
80e6b6df
EZ
2506@cindex baud, in serial connections
2507@cindex bytesize, in serial connections
2508@cindex parity, in serial connections
2509@cindex stopbits, in serial connections
2510@cindex flowcontrol, in serial connections
2511
2512This functions configures a serial port connection. Arguments are
2513specified as keyword/argument pairs. Attributes that are not given
2514are re-initialized from the process's current configuration (available
2515via the function @code{process-contact}) or set to reasonable default
2516values. The following arguments are defined:
c73e02fa
GM
2517
2518@table @code
80e6b6df
EZ
2519@item :process @var{process}
2520@itemx :name @var{name}
2521@itemx :buffer @var{buffer}
2522@itemx :port @var{port}
c73e02fa
GM
2523Any of these arguments can be given to identify the process that is to
2524be configured. If none of these arguments is given, the current
2525buffer's process is used.
2526
2527@item :speed @var{speed}
545c2782
EZ
2528The speed of the serial port in bits per second, a.k.a.@: @dfn{baud
2529rate}. The value can be any number, but most serial ports work only
2530at a few defined values between 1200 and 115200, with 9600 being the
2531most common value. If @var{speed} is @code{nil}, the function ignores
2532all other arguments and does not configure the port. This may be
2533useful for special serial ports such as Bluetooth-to-serial converters
2534which can only be configured through AT commands sent through the
538395d9
EZ
2535connection. The value of @code{nil} for @var{speed} is valid only for
2536connections that were already opened by a previous call to
80e6b6df 2537@code{make-serial-process} or @code{serial-term}.
c73e02fa
GM
2538
2539@item :bytesize @var{bytesize}
80e6b6df
EZ
2540The number of bits per byte, which can be 7 or 8. If @var{bytesize}
2541is not given or @code{nil}, it defaults to 8.
c73e02fa
GM
2542
2543@item :parity @var{parity}
80e6b6df 2544The value can be @code{nil} (don't use parity), the symbol
c73e02fa 2545@code{odd} (use odd parity), or the symbol @code{even} (use even
80e6b6df 2546parity). If @var{parity} is not given, it defaults to no parity.
c73e02fa
GM
2547
2548@item :stopbits @var{stopbits}
80e6b6df
EZ
2549The number of stopbits used to terminate a transmission
2550of each byte. @var{stopbits} can be 1 or 2. If @var{stopbits} is not
2551given or @code{nil}, it defaults to 1.
c73e02fa
GM
2552
2553@item :flowcontrol @var{flowcontrol}
80e6b6df
EZ
2554The type of flow control to use for this connection, which is either
2555@code{nil} (don't use flow control), the symbol @code{hw} (use RTS/CTS
2556hardware flow control), or the symbol @code{sw} (use XON/XOFF software
2557flow control). If @var{flowcontrol} is not given, it defaults to no
2558flow control.
c73e02fa
GM
2559@end table
2560
049bcbcb
CY
2561@code{serial-process-configure} is called by
2562@code{make-serial-process} for the initial configuration of the serial
2563port.
c73e02fa
GM
2564@end defun
2565
b8d4c8d0
GM
2566@node Byte Packing
2567@section Packing and Unpacking Byte Arrays
2568@cindex byte packing and unpacking
2569
2570 This section describes how to pack and unpack arrays of bytes,
2571usually for binary network protocols. These functions convert byte arrays
2572to alists, and vice versa. The byte array can be represented as a
2573unibyte string or as a vector of integers, while the alist associates
2574symbols either with fixed-size objects or with recursive sub-alists.
2575
2576@cindex serializing
2577@cindex deserializing
2578@cindex packing
2579@cindex unpacking
2580 Conversion from byte arrays to nested alists is also known as
2581@dfn{deserializing} or @dfn{unpacking}, while going in the opposite
2582direction is also known as @dfn{serializing} or @dfn{packing}.
2583
2584@menu
2585* Bindat Spec:: Describing data layout.
2586* Bindat Functions:: Doing the unpacking and packing.
2587* Bindat Examples:: Samples of what bindat.el can do for you!
2588@end menu
2589
2590@node Bindat Spec
2591@subsection Describing Data Layout
2592
2593 To control unpacking and packing, you write a @dfn{data layout
2594specification}, a special nested list describing named and typed
2595@dfn{fields}. This specification controls length of each field to be
2596processed, and how to pack or unpack it. We normally keep bindat specs
2597in variables whose names end in @samp{-bindat-spec}; that kind of name
2598is automatically recognized as ``risky.''
2599
2600@cindex endianness
2601@cindex big endian
2602@cindex little endian
2603@cindex network byte ordering
2604 A field's @dfn{type} describes the size (in bytes) of the object
2605that the field represents and, in the case of multibyte fields, how
2606the bytes are ordered within the field. The two possible orderings
2607are ``big endian'' (also known as ``network byte ordering'') and
2608``little endian.'' For instance, the number @code{#x23cd} (decimal
26099165) in big endian would be the two bytes @code{#x23} @code{#xcd};
2610and in little endian, @code{#xcd} @code{#x23}. Here are the possible
2611type values:
2612
2613@table @code
2614@item u8
2615@itemx byte
2616Unsigned byte, with length 1.
2617
2618@item u16
2619@itemx word
2620@itemx short
2621Unsigned integer in network byte order, with length 2.
2622
2623@item u24
2624Unsigned integer in network byte order, with length 3.
2625
2626@item u32
2627@itemx dword
2628@itemx long
2629Unsigned integer in network byte order, with length 4.
2630Note: These values may be limited by Emacs' integer implementation limits.
2631
2632@item u16r
2633@itemx u24r
2634@itemx u32r
2635Unsigned integer in little endian order, with length 2, 3 and 4, respectively.
2636
2637@item str @var{len}
2638String of length @var{len}.
2639
2640@item strz @var{len}
2641Zero-terminated string, in a fixed-size field with length @var{len}.
2642
2643@item vec @var{len} [@var{type}]
2644Vector of @var{len} elements of type @var{type}, or bytes if not
2645@var{type} is specified.
2646The @var{type} is any of the simple types above, or another vector
2647specified as a list @code{(vec @var{len} [@var{type}])}.
2648
2649@item ip
2650Four-byte vector representing an Internet address. For example:
2651@code{[127 0 0 1]} for localhost.
2652
2653@item bits @var{len}
2654List of set bits in @var{len} bytes. The bytes are taken in big
2655endian order and the bits are numbered starting with @code{8 *
2656@var{len} @minus{} 1} and ending with zero. For example: @code{bits
26572} unpacks @code{#x28} @code{#x1c} to @code{(2 3 4 11 13)} and
2658@code{#x1c} @code{#x28} to @code{(3 5 10 11 12)}.
2659
2660@item (eval @var{form})
2661@var{form} is a Lisp expression evaluated at the moment the field is
2662unpacked or packed. The result of the evaluation should be one of the
2663above-listed type specifications.
2664@end table
2665
2666For a fixed-size field, the length @var{len} is given as an integer
2667specifying the number of bytes in the field.
2668
2669When the length of a field is not fixed, it typically depends on the
2670value of a preceding field. In this case, the length @var{len} can be
2671given either as a list @code{(@var{name} ...)} identifying a
2672@dfn{field name} in the format specified for @code{bindat-get-field}
2673below, or by an expression @code{(eval @var{form})} where @var{form}
2674should evaluate to an integer, specifying the field length.
2675
2676A field specification generally has the form @code{([@var{name}]
2677@var{handler})}. The square braces indicate that @var{name} is
2678optional. (Don't use names that are symbols meaningful as type
2679specifications (above) or handler specifications (below), since that
2680would be ambiguous.) @var{name} can be a symbol or the expression
2681@code{(eval @var{form})}, in which case @var{form} should evaluate to
2682a symbol.
2683
2684@var{handler} describes how to unpack or pack the field and can be one
2685of the following:
2686
2687@table @code
2688@item @var{type}
2689Unpack/pack this field according to the type specification @var{type}.
2690
2691@item eval @var{form}
2692Evaluate @var{form}, a Lisp expression, for side-effect only. If the
2693field name is specified, the value is bound to that field name.
2694
2695@item fill @var{len}
2696Skip @var{len} bytes. In packing, this leaves them unchanged,
2697which normally means they remain zero. In unpacking, this means
2698they are ignored.
2699
2700@item align @var{len}
2701Skip to the next multiple of @var{len} bytes.
2702
2703@item struct @var{spec-name}
2704Process @var{spec-name} as a sub-specification. This describes a
2705structure nested within another structure.
2706
2707@item union @var{form} (@var{tag} @var{spec})@dots{}
2708@c ??? I don't see how one would actually use this.
2709@c ??? what kind of expression would be useful for @var{form}?
2710Evaluate @var{form}, a Lisp expression, find the first @var{tag}
2711that matches it, and process its associated data layout specification
2712@var{spec}. Matching can occur in one of three ways:
2713
2714@itemize
2715@item
2716If a @var{tag} has the form @code{(eval @var{expr})}, evaluate
2717@var{expr} with the variable @code{tag} dynamically bound to the value
2718of @var{form}. A non-@code{nil} result indicates a match.
2719
2720@item
2721@var{tag} matches if it is @code{equal} to the value of @var{form}.
2722
2723@item
2724@var{tag} matches unconditionally if it is @code{t}.
2725@end itemize
2726
2727@item repeat @var{count} @var{field-specs}@dots{}
2728Process the @var{field-specs} recursively, in order, then repeat
2729starting from the first one, processing all the specs @var{count}
2730times overall. The @var{count} is given using the same formats as a
2731field length---if an @code{eval} form is used, it is evaluated just once.
2732For correct operation, each spec in @var{field-specs} must include a name.
2733@end table
2734
2735For the @code{(eval @var{form})} forms used in a bindat specification,
2736the @var{form} can access and update these dynamically bound variables
2737during evaluation:
2738
2739@table @code
2740@item last
2741Value of the last field processed.
2742
2743@item bindat-raw
2744The data as a byte array.
2745
2746@item bindat-idx
2747Current index (within @code{bindat-raw}) for unpacking or packing.
2748
2749@item struct
2750The alist containing the structured data that have been unpacked so
2751far, or the entire structure being packed. You can use
2752@code{bindat-get-field} to access specific fields of this structure.
2753
2754@item count
2755@itemx index
2756Inside a @code{repeat} block, these contain the maximum number of
2757repetitions (as specified by the @var{count} parameter), and the
2758current repetition number (counting from 0). Setting @code{count} to
2759zero will terminate the inner-most repeat block after the current
2760repetition has completed.
2761@end table
2762
2763@node Bindat Functions
2764@subsection Functions to Unpack and Pack Bytes
2765
2766 In the following documentation, @var{spec} refers to a data layout
2767specification, @code{bindat-raw} to a byte array, and @var{struct} to an
2768alist representing unpacked field data.
2769
2770@defun bindat-unpack spec bindat-raw &optional bindat-idx
2771This function unpacks data from the unibyte string or byte
2772array @code{bindat-raw}
2773according to @var{spec}. Normally this starts unpacking at the
2774beginning of the byte array, but if @var{bindat-idx} is non-@code{nil}, it
2775specifies a zero-based starting position to use instead.
2776
2777The value is an alist or nested alist in which each element describes
2778one unpacked field.
2779@end defun
2780
2781@defun bindat-get-field struct &rest name
2782This function selects a field's data from the nested alist
2783@var{struct}. Usually @var{struct} was returned by
2784@code{bindat-unpack}. If @var{name} corresponds to just one argument,
2785that means to extract a top-level field value. Multiple @var{name}
2786arguments specify repeated lookup of sub-structures. An integer name
2787acts as an array index.
2788
2789For example, if @var{name} is @code{(a b 2 c)}, that means to find
2790field @code{c} in the third element of subfield @code{b} of field
2791@code{a}. (This corresponds to @code{struct.a.b[2].c} in C.)
2792@end defun
2793
2794 Although packing and unpacking operations change the organization of
2795data (in memory), they preserve the data's @dfn{total length}, which is
2796the sum of all the fields' lengths, in bytes. This value is not
2797generally inherent in either the specification or alist alone; instead,
2798both pieces of information contribute to its calculation. Likewise, the
2799length of a string or array being unpacked may be longer than the data's
2800total length as described by the specification.
2801
2802@defun bindat-length spec struct
2803This function returns the total length of the data in @var{struct},
2804according to @var{spec}.
2805@end defun
2806
2807@defun bindat-pack spec struct &optional bindat-raw bindat-idx
2808This function returns a byte array packed according to @var{spec} from
2809the data in the alist @var{struct}. Normally it creates and fills a
2810new byte array starting at the beginning. However, if @var{bindat-raw}
2811is non-@code{nil}, it specifies a pre-allocated unibyte string or vector to
2812pack into. If @var{bindat-idx} is non-@code{nil}, it specifies the starting
2813offset for packing into @code{bindat-raw}.
2814
2815When pre-allocating, you should make sure @code{(length @var{bindat-raw})}
2816meets or exceeds the total length to avoid an out-of-range error.
2817@end defun
2818
2819@defun bindat-ip-to-string ip
2820Convert the Internet address vector @var{ip} to a string in the usual
2821dotted notation.
2822
2823@example
2824(bindat-ip-to-string [127 0 0 1])
2825 @result{} "127.0.0.1"
2826@end example
2827@end defun
2828
2829@node Bindat Examples
2830@subsection Examples of Byte Unpacking and Packing
2831
2832 Here is a complete example of byte unpacking and packing:
2833
2834@lisp
2835(defvar fcookie-index-spec
2836 '((:version u32)
2837 (:count u32)
2838 (:longest u32)
2839 (:shortest u32)
2840 (:flags u32)
2841 (:delim u8)
2842 (:ignored fill 3)
2843 (:offset repeat (:count)
2844 (:foo u32)))
2845 "Description of a fortune cookie index file's contents.")
2846
2847(defun fcookie (cookies &optional index)
2848 "Display a random fortune cookie from file COOKIES.
2849Optional second arg INDEX specifies the associated index
2850filename, which is by default constructed by appending
2851\".dat\" to COOKIES. Display cookie text in possibly
2852new buffer \"*Fortune Cookie: BASENAME*\" where BASENAME
2853is COOKIES without the directory part."
2854 (interactive "fCookies file: ")
2855 (let* ((info (with-temp-buffer
2856 (insert-file-contents-literally
2857 (or index (concat cookies ".dat")))
2858 (bindat-unpack fcookie-index-spec
2859 (buffer-string))))
2860 (sel (random (bindat-get-field info :count)))
2861 (beg (cdar (bindat-get-field info :offset sel)))
2862 (end (or (cdar (bindat-get-field info
2863 :offset (1+ sel)))
2864 (nth 7 (file-attributes cookies)))))
2865 (switch-to-buffer
2866 (get-buffer-create
2867 (format "*Fortune Cookie: %s*"
2868 (file-name-nondirectory cookies))))
2869 (erase-buffer)
2870 (insert-file-contents-literally
2871 cookies nil beg (- end 3))))
2872
2873(defun fcookie-create-index (cookies &optional index delim)
2874 "Scan file COOKIES, and write out its index file.
2875Optional second arg INDEX specifies the index filename,
2876which is by default constructed by appending \".dat\" to
2877COOKIES. Optional third arg DELIM specifies the unibyte
2878character which, when found on a line of its own in
2879COOKIES, indicates the border between entries."
2880 (interactive "fCookies file: ")
2881 (setq delim (or delim ?%))
2882 (let ((delim-line (format "\n%c\n" delim))
2883 (count 0)
2884 (max 0)
2885 min p q len offsets)
2886 (unless (= 3 (string-bytes delim-line))
2887 (error "Delimiter cannot be represented in one byte"))
2888 (with-temp-buffer
2889 (insert-file-contents-literally cookies)
2890 (while (and (setq p (point))
2891 (search-forward delim-line (point-max) t)
2892 (setq len (- (point) 3 p)))
2893 (setq count (1+ count)
2894 max (max max len)
2895 min (min (or min max) len)
2896 offsets (cons (1- p) offsets))))
2897 (with-temp-buffer
2898 (set-buffer-multibyte nil)
2899 (insert
2900 (bindat-pack
2901 fcookie-index-spec
2902 `((:version . 2)
2903 (:count . ,count)
2904 (:longest . ,max)
2905 (:shortest . ,min)
2906 (:flags . 0)
2907 (:delim . ,delim)
2908 (:offset . ,(mapcar (lambda (o)
2909 (list (cons :foo o)))
2910 (nreverse offsets))))))
2911 (let ((coding-system-for-write 'raw-text-unix))
2912 (write-file (or index (concat cookies ".dat")))))))
2913@end lisp
2914
2915Following is an example of defining and unpacking a complex structure.
2916Consider the following C structures:
2917
2918@example
2919struct header @{
2920 unsigned long dest_ip;
2921 unsigned long src_ip;
2922 unsigned short dest_port;
2923 unsigned short src_port;
2924@};
2925
2926struct data @{
2927 unsigned char type;
2928 unsigned char opcode;
2929 unsigned short length; /* In network byte order */
2930 unsigned char id[8]; /* null-terminated string */
2931 unsigned char data[/* (length + 3) & ~3 */];
2932@};
2933
2934struct packet @{
2935 struct header header;
2936 unsigned long counters[2]; /* In little endian order */
2937 unsigned char items;
2938 unsigned char filler[3];
2939 struct data item[/* items */];
2940
2941@};
2942@end example
2943
2944The corresponding data layout specification:
2945
2946@lisp
2947(setq header-spec
2948 '((dest-ip ip)
2949 (src-ip ip)
2950 (dest-port u16)
2951 (src-port u16)))
2952
2953(setq data-spec
2954 '((type u8)
2955 (opcode u8)
2956 (length u16) ;; network byte order
2957 (id strz 8)
2958 (data vec (length))
2959 (align 4)))
2960
2961(setq packet-spec
2962 '((header struct header-spec)
2963 (counters vec 2 u32r) ;; little endian order
2964 (items u8)
2965 (fill 3)
2966 (item repeat (items)
2967 (struct data-spec))))
2968@end lisp
2969
2970A binary data representation:
2971
2972@lisp
2973(setq binary-data
2974 [ 192 168 1 100 192 168 1 101 01 28 21 32
2975 160 134 1 0 5 1 0 0 2 0 0 0
2976 2 3 0 5 ?A ?B ?C ?D ?E ?F 0 0 1 2 3 4 5 0 0 0
2977 1 4 0 7 ?B ?C ?D ?E ?F ?G 0 0 6 7 8 9 10 11 12 0 ])
2978@end lisp
2979
2980The corresponding decoded structure:
2981
2982@lisp
2983(setq decoded (bindat-unpack packet-spec binary-data))
2984 @result{}
2985((header
2986 (dest-ip . [192 168 1 100])
2987 (src-ip . [192 168 1 101])
2988 (dest-port . 284)
2989 (src-port . 5408))
2990 (counters . [100000 261])
2991 (items . 2)
2992 (item ((data . [1 2 3 4 5])
2993 (id . "ABCDEF")
2994 (length . 5)
2995 (opcode . 3)
2996 (type . 2))
2997 ((data . [6 7 8 9 10 11 12])
2998 (id . "BCDEFG")
2999 (length . 7)
3000 (opcode . 4)
3001 (type . 1))))
3002@end lisp
3003
3004Fetching data from this structure:
3005
3006@lisp
3007(bindat-get-field decoded 'item 1 'id)
3008 @result{} "BCDEFG"
3009@end lisp