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