Merge changes made in Gnus trunk.
[bpt/emacs.git] / src / process.c
CommitLineData
d0d6b7c5 1/* Asynchronous subprocess control for GNU Emacs.
0b5538bd 2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
63136da6 3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
114f9c96 4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
d0d6b7c5
JB
5
6This file is part of GNU Emacs.
7
9ec0b715 8GNU Emacs is free software: you can redistribute it and/or modify
d0d6b7c5 9it under the terms of the GNU General Public License as published by
9ec0b715
GM
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
d0d6b7c5
JB
12
13GNU Emacs is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
9ec0b715 19along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
d0d6b7c5
JB
20
21
18160b98 22#include <config.h>
68c45bf0 23#include <signal.h>
d0d6b7c5
JB
24#include <stdio.h>
25#include <errno.h>
26#include <setjmp.h>
27#include <sys/types.h> /* some typedefs are used in sys/file.h */
28#include <sys/file.h>
29#include <sys/stat.h>
d7306fe6 30#include <setjmp.h>
2026418c
YM
31#ifdef HAVE_INTTYPES_H
32#include <inttypes.h>
33#endif
63136da6 34#include <stdlib.h>
934e2a68 35
93b4f699
RS
36#ifdef HAVE_UNISTD_H
37#include <unistd.h>
38#endif
e98d950b 39#include <fcntl.h>
e98d950b 40
f388c88a
EZ
41/* Only MS-DOS does not define `subprocesses'. */
42#ifdef subprocesses
43
d0d6b7c5
JB
44#include <sys/socket.h>
45#include <netdb.h>
46#include <netinet/in.h>
47#include <arpa/inet.h>
e690ca94
KS
48
49/* Are local (unix) sockets supported? */
4624371d 50#if defined (HAVE_SYS_UN_H)
e690ca94
KS
51#if !defined (AF_LOCAL) && defined (AF_UNIX)
52#define AF_LOCAL AF_UNIX
53#endif
54#ifdef AF_LOCAL
55#define HAVE_LOCAL_SOCKETS
56#include <sys/un.h>
57#endif
58#endif
d0d6b7c5 59
1d29df59 60#if defined(HAVE_SYS_IOCTL_H)
d0d6b7c5 61#include <sys/ioctl.h>
32bc6709
DN
62#if defined(HAVE_NET_IF_H)
63#include <net/if.h>
64#endif /* HAVE_NET_IF_H */
1d29df59 65#endif /* HAVE_SYS_IOCTL_H */
d0d6b7c5
JB
66
67#ifdef NEED_BSDTTY
68#include <bsdtty.h>
69#endif
70
e62cab61
DL
71#ifdef HAVE_SYS_WAIT
72#include <sys/wait.h>
73#endif
d0d6b7c5 74
08116b48
CY
75#ifdef HAVE_RES_INIT
76#include <netinet/in.h>
77#include <arpa/nameser.h>
78#include <resolv.h>
79#endif
80
3d608a86
J
81#ifdef HAVE_UTIL_H
82#include <util.h>
83#endif
84
f388c88a
EZ
85#endif /* subprocesses */
86
fa8459a3 87#include "lisp.h"
d0d6b7c5 88#include "systime.h"
36ebaafa 89#include "systty.h"
d0d6b7c5 90
d0d6b7c5
JB
91#include "window.h"
92#include "buffer.h"
5bbf78c1 93#include "character.h"
0fa1789e 94#include "coding.h"
d0d6b7c5 95#include "process.h"
428a555e 96#include "frame.h"
d0d6b7c5
JB
97#include "termhooks.h"
98#include "termopts.h"
99#include "commands.h"
3ec68006 100#include "keyboard.h"
ececcbec 101#include "blockinput.h"
dfcf069d 102#include "dispextern.h"
e0016554 103#include "composite.h"
30904ab7 104#include "atimer.h"
f388c88a
EZ
105#include "sysselect.h"
106#include "syssignal.h"
107#include "syswait.h"
d0d6b7c5 108
872870b2
JD
109#if defined (USE_GTK) || defined (HAVE_GCONF)
110#include "xgselect.h"
111#endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
3d608a86
J
112#ifdef HAVE_NS
113#include "nsterm.h"
114#endif
fdb183d6
DN
115extern int timers_run;
116
117Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
118Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
119Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
120Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
121Lisp_Object QCname, QCtype;
122\f
123/* Non-zero if keyboard input is on hold, zero otherwise. */
124
125static int kbd_is_on_hold;
126
127/* Nonzero means delete a process right away if it exits. */
128static int delete_exited_processes;
129
130/* Nonzero means don't run process sentinels. This is used
131 when exiting. */
132int inhibit_sentinels;
133
f388c88a
EZ
134#ifdef subprocesses
135
dd2281ae 136Lisp_Object Qprocessp;
324e68ba 137Lisp_Object Qrun, Qstop, Qsignal;
e690ca94 138Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
f00c449b 139Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
d888760c 140Lisp_Object Qreal, Qnetwork, Qserial;
e1652a86
KS
141#ifdef AF_INET6
142Lisp_Object Qipv6;
143#endif
d888760c
GM
144Lisp_Object QCport, QCspeed, QCprocess;
145Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
146Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
f388c88a 147Lisp_Object QCbuffer, QChost, QCservice;
e690ca94 148Lisp_Object QClocal, QCremote, QCcoding;
9057ff80 149Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
faa7db08 150Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
6545aada 151Lisp_Object Qlast_nonmenu_event;
3635ecad
JR
152/* QCfamily is declared and initialized in xfaces.c,
153 QCfilter in keyboard.c. */
154extern Lisp_Object QCfamily, QCfilter;
155
d0d6b7c5
JB
156/* Qexit is declared and initialized in eval.c. */
157
e0f712ba
AC
158/* QCfamily is defined in xfaces.c. */
159extern Lisp_Object QCfamily;
160/* QCfilter is defined in keyboard.c. */
161extern Lisp_Object QCfilter;
162
d888760c
GM
163#define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
164#define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
165#define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
166#define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
d0d6b7c5
JB
167
168/* Define first descriptor number available for subprocesses. */
d0d6b7c5 169#define FIRST_PROC_DESC 3
d0d6b7c5
JB
170
171/* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
172 testing SIGCHLD. */
173
174#if !defined (SIGCHLD) && defined (SIGCLD)
175#define SIGCHLD SIGCLD
176#endif /* SIGCLD */
177
8ea90aa3 178extern const char *get_operating_system_release (void);
41d03b9a 179
d888760c
GM
180/* From sysdep.c or w32.c */
181extern int serial_open (char *port);
182extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
d888760c 183
5f0929a7
RS
184#ifndef HAVE_H_ERRNO
185extern int h_errno;
186#endif
187
d0d6b7c5
JB
188/* t means use pty, nil means use a pipe,
189 maybe other values to come. */
dd2281ae 190static Lisp_Object Vprocess_connection_type;
d0d6b7c5 191
17d02632
KH
192/* These next two vars are non-static since sysdep.c uses them in the
193 emulation of `select'. */
d0d6b7c5 194/* Number of events of change of status of a process. */
17d02632 195int process_tick;
d0d6b7c5 196/* Number of events for which the user or sentinel has been notified. */
17d02632 197int update_tick;
d0d6b7c5 198
dd2a17ab
KS
199/* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
200
201#ifdef BROKEN_NON_BLOCKING_CONNECT
202#undef NON_BLOCKING_CONNECT
203#else
204#ifndef NON_BLOCKING_CONNECT
dd2a17ab
KS
205#ifdef HAVE_SELECT
206#if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
207#if defined (O_NONBLOCK) || defined (O_NDELAY)
208#if defined (EWOULDBLOCK) || defined (EINPROGRESS)
209#define NON_BLOCKING_CONNECT
210#endif /* EWOULDBLOCK || EINPROGRESS */
211#endif /* O_NONBLOCK || O_NDELAY */
212#endif /* HAVE_GETPEERNAME || GNU_LINUX */
213#endif /* HAVE_SELECT */
dd2a17ab
KS
214#endif /* NON_BLOCKING_CONNECT */
215#endif /* BROKEN_NON_BLOCKING_CONNECT */
216
e690ca94
KS
217/* Define DATAGRAM_SOCKETS if datagrams can be used safely on
218 this system. We need to read full packets, so we need a
219 "non-destructive" select. So we require either native select,
220 or emulation of select using FIONREAD. */
221
e690ca94
KS
222#ifdef BROKEN_DATAGRAM_SOCKETS
223#undef DATAGRAM_SOCKETS
224#else
225#ifndef DATAGRAM_SOCKETS
e690ca94
KS
226#if defined (HAVE_SELECT) || defined (FIONREAD)
227#if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
228#define DATAGRAM_SOCKETS
229#endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
230#endif /* HAVE_SELECT || FIONREAD */
e690ca94
KS
231#endif /* DATAGRAM_SOCKETS */
232#endif /* BROKEN_DATAGRAM_SOCKETS */
233
f00c449b
SM
234#if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
235# define HAVE_SEQPACKET
236#endif
237
6b61353c
KH
238#if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
239#ifdef EMACS_HAS_USECS
240#define ADAPTIVE_READ_BUFFERING
241#endif
242#endif
243
244#ifdef ADAPTIVE_READ_BUFFERING
245#define READ_OUTPUT_DELAY_INCREMENT 10000
246#define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
247#define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
248
db853b7a
KS
249/* Number of processes which have a non-zero read_output_delay,
250 and therefore might be delayed for adaptive read buffering. */
6b61353c
KH
251
252static int process_output_delay_count;
253
db853b7a 254/* Non-zero if any process has non-nil read_output_skip. */
6b61353c
KH
255
256static int process_output_skip;
257
258/* Non-nil means to delay reading process output to improve buffering.
259 A value of t means that delay is reset after each send, any other
db853b7a
KS
260 non-nil value does not reset the delay. A value of nil disables
261 adaptive read buffering completely. */
6b61353c
KH
262static Lisp_Object Vprocess_adaptive_read_buffering;
263#else
264#define process_output_delay_count 0
265#endif
266
f57e2426
J
267static int keyboard_bit_set (SELECT_TYPE *);
268static void deactivate_process (Lisp_Object);
269static void status_notify (struct Lisp_Process *);
270static int read_process_output (Lisp_Object, int);
271static void create_pty (Lisp_Object);
41d03b9a 272
583dcae4 273/* If we support a window system, turn on the code to poll periodically
44ade2e9 274 to detect C-g. It isn't actually used when doing interrupt input. */
583dcae4 275#ifdef HAVE_WINDOW_SYSTEM
44ade2e9
RS
276#define POLL_FOR_INPUT
277#endif
278
d3da34e0
JB
279static Lisp_Object get_process (register Lisp_Object name);
280static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
84af9896 281
f388c88a
EZ
282/* Mask of bits indicating the descriptors that we wait for input on. */
283
284static SELECT_TYPE input_wait_mask;
285
994d9841 286/* Mask that excludes keyboard input descriptor(s). */
a69281ff
RS
287
288static SELECT_TYPE non_keyboard_wait_mask;
289
994d9841 290/* Mask that excludes process input descriptor(s). */
b5dc1c83
RS
291
292static SELECT_TYPE non_process_wait_mask;
293
994d9841
NR
294/* Mask for the gpm mouse input descriptor. */
295
296static SELECT_TYPE gpm_wait_mask;
297
bad49fc7 298#ifdef NON_BLOCKING_CONNECT
dd2a17ab
KS
299/* Mask of bits indicating the descriptors that we wait for connect to
300 complete on. Once they complete, they are removed from this mask
301 and added to the input_wait_mask and non_keyboard_wait_mask. */
302
303static SELECT_TYPE connect_wait_mask;
304
305/* Number of bits set in connect_wait_mask. */
306static int num_pending_connects;
307
bad49fc7 308#define IF_NON_BLOCKING_CONNECT(s) s
f388c88a 309#else /* NON_BLOCKING_CONNECT */
bad49fc7 310#define IF_NON_BLOCKING_CONNECT(s)
f388c88a 311#endif /* NON_BLOCKING_CONNECT */
bad49fc7 312
7d0e672e
RS
313/* The largest descriptor currently in use for a process object. */
314static int max_process_desc;
315
a69281ff
RS
316/* The largest descriptor currently in use for keyboard input. */
317static int max_keyboard_desc;
d0d6b7c5 318
994d9841
NR
319/* The largest descriptor currently in use for gpm mouse input. */
320static int max_gpm_desc;
321
d0d6b7c5 322/* Indexed by descriptor, gives the process (if any) for that descriptor */
41f3aa98 323Lisp_Object chan_process[MAXDESC];
d0d6b7c5
JB
324
325/* Alist of elements (NAME . PROCESS) */
41f3aa98 326Lisp_Object Vprocess_alist;
d0d6b7c5
JB
327
328/* Buffered-ahead input char from process, indexed by channel.
329 -1 means empty (no char is buffered).
330 Used on sys V where the only way to tell if there is any
331 output from the process is to read at least one char.
332 Always -1 on systems that support FIONREAD. */
333
e98d950b
RS
334/* Don't make static; need to access externally. */
335int proc_buffered_char[MAXDESC];
dd2281ae 336
0fa1789e 337/* Table of `struct coding-system' for each process. */
c7580538
KH
338static struct coding_system *proc_decode_coding_system[MAXDESC];
339static struct coding_system *proc_encode_coding_system[MAXDESC];
0fa1789e 340
e690ca94
KS
341#ifdef DATAGRAM_SOCKETS
342/* Table of `partner address' for datagram sockets. */
343struct sockaddr_and_len {
344 struct sockaddr *sa;
345 int len;
346} datagram_address[MAXDESC];
347#define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
60f0fb11 348#define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
e690ca94
KS
349#else
350#define DATAGRAM_CHAN_P(chan) (0)
351#define DATAGRAM_CONN_P(proc) (0)
352#endif
353
93b4f699
RS
354/* Maximum number of bytes to send to a pty without an eof. */
355static int pty_max_bytes;
3b9a3dfa 356
875e6b94 357#ifdef HAVE_PTYS
e62cab61
DL
358#ifdef HAVE_PTY_H
359#include <pty.h>
360#endif
875e6b94 361/* The file name of the pty opened by allocate_pty. */
3b9a3dfa
RS
362
363static char pty_name[24];
875e6b94 364#endif
d0d6b7c5
JB
365\f
366/* Compute the Lisp form of the process status, p->status, from
367 the numeric status that was returned by `wait'. */
368
bba104c1 369static Lisp_Object status_convert (int);
f9738840 370
ff6daed3 371static void
d3da34e0 372update_status (struct Lisp_Process *p)
d0d6b7c5 373{
6bfd98e7 374 eassert (p->raw_status_new);
bba104c1 375 p->status = status_convert (p->raw_status);
6bfd98e7 376 p->raw_status_new = 0;
d0d6b7c5
JB
377}
378
177c0ea7 379/* Convert a process status word in Unix format to
d0d6b7c5
JB
380 the list that we use internally. */
381
ff6daed3 382static Lisp_Object
bba104c1 383status_convert (int w)
d0d6b7c5
JB
384{
385 if (WIFSTOPPED (w))
386 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
387 else if (WIFEXITED (w))
388 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
389 WCOREDUMP (w) ? Qt : Qnil));
390 else if (WIFSIGNALED (w))
391 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
392 WCOREDUMP (w) ? Qt : Qnil));
393 else
394 return Qrun;
395}
396
397/* Given a status-list, extract the three pieces of information
398 and store them individually through the three pointers. */
399
ff6daed3 400static void
d3da34e0 401decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
d0d6b7c5
JB
402{
403 Lisp_Object tem;
404
bcd69aea 405 if (SYMBOLP (l))
d0d6b7c5
JB
406 {
407 *symbol = l;
408 *code = 0;
409 *coredump = 0;
410 }
411 else
412 {
70949dac
KR
413 *symbol = XCAR (l);
414 tem = XCDR (l);
415 *code = XFASTINT (XCAR (tem));
416 tem = XCDR (tem);
d0d6b7c5
JB
417 *coredump = !NILP (tem);
418 }
419}
420
421/* Return a string describing a process status list. */
422
116c423c 423static Lisp_Object
d3da34e0 424status_message (struct Lisp_Process *p)
d0d6b7c5 425{
116c423c 426 Lisp_Object status = p->status;
d0d6b7c5
JB
427 Lisp_Object symbol;
428 int code, coredump;
429 Lisp_Object string, string2;
430
431 decode_status (status, &symbol, &code, &coredump);
432
433 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
434 {
68c45bf0 435 char *signame;
ca9c0567 436 synchronize_system_messages_locale ();
68c45bf0 437 signame = strsignal (code);
b97ad9ea 438 if (signame == 0)
66bd43d1
KH
439 string = build_string ("unknown");
440 else
441 {
442 int c1, c2;
443
444 string = make_unibyte_string (signame, strlen (signame));
445 if (! NILP (Vlocale_coding_system))
446 string = (code_convert_string_norecord
447 (string, Vlocale_coding_system, 0));
62a6e103 448 c1 = STRING_CHAR ((char *) SDATA (string));
66bd43d1
KH
449 c2 = DOWNCASE (c1);
450 if (c1 != c2)
4735b74e 451 Faset (string, make_number (0), make_number (c2));
66bd43d1 452 }
d0d6b7c5 453 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
d0d6b7c5
JB
454 return concat2 (string, string2);
455 }
456 else if (EQ (symbol, Qexit))
457 {
116c423c
KS
458 if (NETCONN1_P (p))
459 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
d0d6b7c5
JB
460 if (code == 0)
461 return build_string ("finished\n");
f2980264 462 string = Fnumber_to_string (make_number (code));
d0d6b7c5 463 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
e690ca94
KS
464 return concat3 (build_string ("exited abnormally with code "),
465 string, string2);
d0d6b7c5 466 }
dd2a17ab
KS
467 else if (EQ (symbol, Qfailed))
468 {
469 string = Fnumber_to_string (make_number (code));
470 string2 = build_string ("\n");
e690ca94
KS
471 return concat3 (build_string ("failed with code "),
472 string, string2);
dd2a17ab 473 }
d0d6b7c5
JB
474 else
475 return Fcopy_sequence (Fsymbol_name (symbol));
476}
477\f
478#ifdef HAVE_PTYS
d0d6b7c5 479
875e6b94
KH
480/* Open an available pty, returning a file descriptor.
481 Return -1 on failure.
482 The file name of the terminal corresponding to the pty
483 is left in the variable pty_name. */
484
ff6daed3 485static int
d3da34e0 486allocate_pty (void)
d0d6b7c5 487{
dfcf069d 488 register int c, i;
d0d6b7c5
JB
489 int fd;
490
491#ifdef PTY_ITERATION
492 PTY_ITERATION
493#else
494 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
495 for (i = 0; i < 16; i++)
496#endif
497 {
26d7389d 498 struct stat stb; /* Used in some PTY_OPEN. */
d0d6b7c5
JB
499#ifdef PTY_NAME_SPRINTF
500 PTY_NAME_SPRINTF
d0d6b7c5
JB
501#else
502 sprintf (pty_name, "/dev/pty%c%x", c, i);
d0d6b7c5
JB
503#endif /* no PTY_NAME_SPRINTF */
504
4d7c105e
RS
505#ifdef PTY_OPEN
506 PTY_OPEN;
507#else /* no PTY_OPEN */
34967d0f 508 {
34967d0f
SM
509 { /* Some systems name their pseudoterminals so that there are gaps in
510 the usual sequence - for example, on HP9000/S700 systems, there
511 are no pseudoterminals with names ending in 'f'. So we wait for
512 three failures in a row before deciding that we've reached the
513 end of the ptys. */
514 int failed_count = 0;
f3d9532b 515
34967d0f
SM
516 if (stat (pty_name, &stb) < 0)
517 {
518 failed_count++;
519 if (failed_count >= 3)
520 return -1;
521 }
522 else
523 failed_count = 0;
32676c08 524 }
34967d0f
SM
525# ifdef O_NONBLOCK
526 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
527# else
528 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
529# endif
34967d0f 530 }
4d7c105e 531#endif /* no PTY_OPEN */
d0d6b7c5
JB
532
533 if (fd >= 0)
534 {
535 /* check to make certain that both sides are available
536 this avoids a nasty yet stupid bug in rlogins */
537#ifdef PTY_TTY_NAME_SPRINTF
538 PTY_TTY_NAME_SPRINTF
d0d6b7c5 539#else
63136da6 540 sprintf (pty_name, "/dev/tty%c%x", c, i);
d0d6b7c5 541#endif /* no PTY_TTY_NAME_SPRINTF */
d0d6b7c5
JB
542 if (access (pty_name, 6) != 0)
543 {
68c45bf0 544 emacs_close (fd);
132d0475 545# ifndef __sgi
d0d6b7c5 546 continue;
34967d0f 547# else
d0d6b7c5 548 return -1;
132d0475 549# endif /* __sgi */
d0d6b7c5 550 }
d0d6b7c5
JB
551 setup_pty (fd);
552 return fd;
553 }
554 }
555 return -1;
556}
557#endif /* HAVE_PTYS */
558\f
ff6daed3 559static Lisp_Object
d3da34e0 560make_process (Lisp_Object name)
d0d6b7c5
JB
561{
562 register Lisp_Object val, tem, name1;
563 register struct Lisp_Process *p;
564 char suffix[10];
565 register int i;
566
98423852 567 p = allocate_process ();
23d6bb9c 568
60f0fb11
SM
569 p->infd = -1;
570 p->outfd = -1;
571 p->tick = 0;
572 p->update_tick = 0;
6bfd98e7 573 p->pid = 0;
fd41ad98 574 p->pty_flag = 0;
6bfd98e7 575 p->raw_status_new = 0;
d0d6b7c5
JB
576 p->status = Qrun;
577 p->mark = Fmake_marker ();
847c048e 578 p->kill_without_query = 0;
d0d6b7c5 579
6b61353c 580#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11
SM
581 p->adaptive_read_buffering = 0;
582 p->read_output_delay = 0;
583 p->read_output_skip = 0;
6b61353c
KH
584#endif
585
d0d6b7c5
JB
586 /* If name is already in use, modify it until it is unused. */
587
588 name1 = name;
589 for (i = 1; ; i++)
590 {
591 tem = Fget_process (name1);
592 if (NILP (tem)) break;
593 sprintf (suffix, "<%d>", i);
594 name1 = concat2 (name, build_string (suffix));
595 }
596 name = name1;
597 p->name = name;
23d6bb9c 598 XSETPROCESS (val, p);
d0d6b7c5
JB
599 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
600 return val;
601}
602
ff6daed3 603static void
d3da34e0 604remove_process (register Lisp_Object proc)
d0d6b7c5
JB
605{
606 register Lisp_Object pair;
607
608 pair = Frassq (proc, Vprocess_alist);
609 Vprocess_alist = Fdelq (pair, Vprocess_alist);
d0d6b7c5
JB
610
611 deactivate_process (proc);
612}
03f04413 613
d0d6b7c5
JB
614\f
615DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
fdb82f93 616 doc: /* Return t if OBJECT is a process. */)
5842a27b 617 (Lisp_Object object)
d0d6b7c5 618{
4ee3e309 619 return PROCESSP (object) ? Qt : Qnil;
d0d6b7c5
JB
620}
621
622DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
fdb82f93 623 doc: /* Return the process named NAME, or nil if there is none. */)
5842a27b 624 (register Lisp_Object name)
d0d6b7c5 625{
bcd69aea 626 if (PROCESSP (name))
d0d6b7c5 627 return name;
b7826503 628 CHECK_STRING (name);
d0d6b7c5
JB
629 return Fcdr (Fassoc (name, Vprocess_alist));
630}
631
ebb9e16f
JB
632/* This is how commands for the user decode process arguments. It
633 accepts a process, a process name, a buffer, a buffer name, or nil.
634 Buffers denote the first process in the buffer, and nil denotes the
635 current buffer. */
d0d6b7c5 636
77b221b1 637static Lisp_Object
d3da34e0 638get_process (register Lisp_Object name)
d0d6b7c5 639{
1619761d
KH
640 register Lisp_Object proc, obj;
641 if (STRINGP (name))
642 {
643 obj = Fget_process (name);
644 if (NILP (obj))
645 obj = Fget_buffer (name);
646 if (NILP (obj))
d5db4077 647 error ("Process %s does not exist", SDATA (name));
1619761d
KH
648 }
649 else if (NILP (name))
650 obj = Fcurrent_buffer ();
d0d6b7c5 651 else
1619761d
KH
652 obj = name;
653
654 /* Now obj should be either a buffer object or a process object.
655 */
656 if (BUFFERP (obj))
d0d6b7c5 657 {
1619761d 658 proc = Fget_buffer_process (obj);
d0d6b7c5 659 if (NILP (proc))
d5db4077 660 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
d0d6b7c5 661 }
d0d6b7c5 662 else
1619761d 663 {
b7826503 664 CHECK_PROCESS (obj);
1619761d
KH
665 proc = obj;
666 }
667 return proc;
d0d6b7c5
JB
668}
669
a5cfdda8
KS
670
671#ifdef SIGCHLD
672/* Fdelete_process promises to immediately forget about the process, but in
673 reality, Emacs needs to remember those processes until they have been
674 treated by sigchld_handler; otherwise this handler would consider the
675 process as being synchronous and say that the synchronous process is
676 dead. */
677static Lisp_Object deleted_pid_list;
678#endif
679
d0d6b7c5 680DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
fdb82f93
PJ
681 doc: /* Delete PROCESS: kill it and forget about it immediately.
682PROCESS may be a process, a buffer, the name of a process or buffer, or
683nil, indicating the current buffer's process. */)
5842a27b 684 (register Lisp_Object process)
d0d6b7c5 685{
ff6daed3
KS
686 register struct Lisp_Process *p;
687
4ee3e309 688 process = get_process (process);
ff6daed3
KS
689 p = XPROCESS (process);
690
6bfd98e7 691 p->raw_status_new = 0;
d888760c 692 if (NETCONN1_P (p) || SERIALCONN1_P (p))
d0d6b7c5 693 {
ff6daed3 694 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
60f0fb11 695 p->tick = ++process_tick;
ff6daed3 696 status_notify (p);
e42bdf01 697 redisplay_preserve_echo_area (13);
d0d6b7c5 698 }
60f0fb11 699 else if (p->infd >= 0)
d0d6b7c5 700 {
a5cfdda8
KS
701#ifdef SIGCHLD
702 Lisp_Object symbol;
d30fe779
EZ
703 /* Assignment to EMACS_INT stops GCC whining about limited range
704 of data type. */
29ed4d51 705 EMACS_INT pid = p->pid;
a5cfdda8
KS
706
707 /* No problem storing the pid here, as it is still in Vprocess_alist. */
d30fe779 708 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
a5cfdda8
KS
709 /* GC treated elements set to nil. */
710 Fdelq (Qnil, deleted_pid_list));
711 /* If the process has already signaled, remove it from the list. */
712 if (p->raw_status_new)
713 update_status (p);
714 symbol = p->status;
715 if (CONSP (p->status))
716 symbol = XCAR (p->status);
717 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
29ed4d51
CY
718 deleted_pid_list
719 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
a5cfdda8
KS
720 else
721#endif
722 {
723 Fkill_process (process, Qnil);
724 /* Do this now, since remove_process will make sigchld_handler do nothing. */
725 p->status
726 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
60f0fb11 727 p->tick = ++process_tick;
a5cfdda8 728 status_notify (p);
e42bdf01 729 redisplay_preserve_echo_area (13);
a5cfdda8 730 }
d0d6b7c5 731 }
4ee3e309 732 remove_process (process);
d0d6b7c5
JB
733 return Qnil;
734}
735\f
736DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
fdb82f93
PJ
737 doc: /* Return the status of PROCESS.
738The returned value is one of the following symbols:
739run -- for a process that is running.
740stop -- for a process stopped but continuable.
741exit -- for a process that has exited.
742signal -- for a process that has got a fatal signal.
743open -- for a network stream connection that is open.
e690ca94 744listen -- for a network stream server that is listening.
fdb82f93 745closed -- for a network stream connection that is closed.
e4984112
KS
746connect -- when waiting for a non-blocking connection to complete.
747failed -- when a non-blocking connection has failed.
fdb82f93
PJ
748nil -- if arg is a process name and no such process exists.
749PROCESS may be a process, a buffer, the name of a process, or
750nil, indicating the current buffer's process. */)
5842a27b 751 (register Lisp_Object process)
d0d6b7c5
JB
752{
753 register struct Lisp_Process *p;
754 register Lisp_Object status;
343f4114 755
4ee3e309
EN
756 if (STRINGP (process))
757 process = Fget_process (process);
343f4114 758 else
4ee3e309 759 process = get_process (process);
343f4114 760
4ee3e309
EN
761 if (NILP (process))
762 return process;
343f4114 763
4ee3e309 764 p = XPROCESS (process);
6bfd98e7 765 if (p->raw_status_new)
d0d6b7c5
JB
766 update_status (p);
767 status = p->status;
bcd69aea 768 if (CONSP (status))
70949dac 769 status = XCAR (status);
d888760c 770 if (NETCONN1_P (p) || SERIALCONN1_P (p))
d0d6b7c5 771 {
e690ca94 772 if (EQ (status, Qexit))
d0d6b7c5 773 status = Qclosed;
e690ca94
KS
774 else if (EQ (p->command, Qt))
775 status = Qstop;
776 else if (EQ (status, Qrun))
777 status = Qopen;
d0d6b7c5
JB
778 }
779 return status;
780}
781
782DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
783 1, 1, 0,
fdb82f93
PJ
784 doc: /* Return the exit status of PROCESS or the signal number that killed it.
785If PROCESS has not yet exited or died, return 0. */)
5842a27b 786 (register Lisp_Object process)
d0d6b7c5 787{
b7826503 788 CHECK_PROCESS (process);
6bfd98e7 789 if (XPROCESS (process)->raw_status_new)
4ee3e309
EN
790 update_status (XPROCESS (process));
791 if (CONSP (XPROCESS (process)->status))
70949dac 792 return XCAR (XCDR (XPROCESS (process)->status));
d0d6b7c5
JB
793 return make_number (0);
794}
795
796DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
fdb82f93 797 doc: /* Return the process id of PROCESS.
f3d9532b 798This is the pid of the external process which PROCESS uses or talks to.
fdb82f93 799For a network connection, this value is nil. */)
5842a27b 800 (register Lisp_Object process)
d0d6b7c5 801{
d30fe779
EZ
802 /* Assignment to EMACS_INT stops GCC whining about limited range of
803 data type. */
804 EMACS_INT pid;
805
b7826503 806 CHECK_PROCESS (process);
d30fe779
EZ
807 pid = XPROCESS (process)->pid;
808 return (pid ? make_fixnum_or_float (pid) : Qnil);
d0d6b7c5
JB
809}
810
811DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
fdb82f93
PJ
812 doc: /* Return the name of PROCESS, as a string.
813This is the name of the program invoked in PROCESS,
814possibly modified to make it unique among process names. */)
5842a27b 815 (register Lisp_Object process)
d0d6b7c5 816{
b7826503 817 CHECK_PROCESS (process);
4ee3e309 818 return XPROCESS (process)->name;
d0d6b7c5
JB
819}
820
821DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
fdb82f93
PJ
822 doc: /* Return the command that was executed to start PROCESS.
823This is a list of strings, the first string being the program executed
824and the rest of the strings being the arguments given to it.
d888760c
GM
825For a network or serial process, this is nil (process is running) or t
826\(process is stopped). */)
5842a27b 827 (register Lisp_Object process)
d0d6b7c5 828{
b7826503 829 CHECK_PROCESS (process);
4ee3e309 830 return XPROCESS (process)->command;
d0d6b7c5
JB
831}
832
3b9a3dfa 833DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
fdb82f93
PJ
834 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
835This is the terminal that the process itself reads and writes on,
836not the name of the pty that Emacs uses to talk with that terminal. */)
5842a27b 837 (register Lisp_Object process)
3b9a3dfa 838{
b7826503 839 CHECK_PROCESS (process);
4ee3e309 840 return XPROCESS (process)->tty_name;
3b9a3dfa
RS
841}
842
d0d6b7c5 843DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
fdb82f93
PJ
844 2, 2, 0,
845 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
5842a27b 846 (register Lisp_Object process, Lisp_Object buffer)
d0d6b7c5 847{
e690ca94
KS
848 struct Lisp_Process *p;
849
b7826503 850 CHECK_PROCESS (process);
d0d6b7c5 851 if (!NILP (buffer))
b7826503 852 CHECK_BUFFER (buffer);
e690ca94
KS
853 p = XPROCESS (process);
854 p->buffer = buffer;
d888760c 855 if (NETCONN1_P (p) || SERIALCONN1_P (p))
e690ca94 856 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
03f04413 857 setup_process_coding_systems (process);
d0d6b7c5
JB
858 return buffer;
859}
860
861DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
fdb82f93
PJ
862 1, 1, 0,
863 doc: /* Return the buffer PROCESS is associated with.
864Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
5842a27b 865 (register Lisp_Object process)
d0d6b7c5 866{
b7826503 867 CHECK_PROCESS (process);
4ee3e309 868 return XPROCESS (process)->buffer;
d0d6b7c5
JB
869}
870
871DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
fdb82f93
PJ
872 1, 1, 0,
873 doc: /* Return the marker for the end of the last output from PROCESS. */)
5842a27b 874 (register Lisp_Object process)
d0d6b7c5 875{
b7826503 876 CHECK_PROCESS (process);
4ee3e309 877 return XPROCESS (process)->mark;
d0d6b7c5
JB
878}
879
880DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
fdb82f93
PJ
881 2, 2, 0,
882 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
7b82c3b6 883A value of t means stop accepting output from the process.
3452df9e
KS
884
885When a process has a filter, its buffer is not used for output.
886Instead, each time it does output, the entire string of output is
177c0ea7 887passed to the filter.
3452df9e 888
fdb82f93 889The filter gets two arguments: the process and the string of output.
3452df9e
KS
890The string argument is normally a multibyte string, except:
891- if the process' input coding system is no-conversion or raw-text,
892 it is a unibyte string (the non-converted input), or else
893- if `default-enable-multibyte-characters' is nil, it is a unibyte
894 string (the result of converting the decoded input multibyte
895 string to unibyte with `string-make-unibyte'). */)
5842a27b 896 (register Lisp_Object process, Lisp_Object filter)
d0d6b7c5 897{
471f86b9 898 struct Lisp_Process *p;
177c0ea7 899
b7826503 900 CHECK_PROCESS (process);
471f86b9
GM
901 p = XPROCESS (process);
902
903 /* Don't signal an error if the process' input file descriptor
904 is closed. This could make debugging Lisp more difficult,
905 for example when doing something like
906
907 (setq process (start-process ...))
908 (debug)
909 (set-process-filter process ...) */
177c0ea7 910
60f0fb11 911 if (p->infd >= 0)
a69281ff 912 {
e690ca94 913 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
471f86b9 914 {
60f0fb11
SM
915 FD_CLR (p->infd, &input_wait_mask);
916 FD_CLR (p->infd, &non_keyboard_wait_mask);
471f86b9 917 }
e690ca94 918 else if (EQ (p->filter, Qt)
d888760c
GM
919 /* Network or serial process not stopped: */
920 && !EQ (p->command, Qt))
471f86b9 921 {
60f0fb11
SM
922 FD_SET (p->infd, &input_wait_mask);
923 FD_SET (p->infd, &non_keyboard_wait_mask);
471f86b9 924 }
a69281ff 925 }
177c0ea7 926
471f86b9 927 p->filter = filter;
d888760c 928 if (NETCONN1_P (p) || SERIALCONN1_P (p))
e690ca94 929 p->childp = Fplist_put (p->childp, QCfilter, filter);
03f04413 930 setup_process_coding_systems (process);
d0d6b7c5
JB
931 return filter;
932}
933
934DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
fdb82f93
PJ
935 1, 1, 0,
936 doc: /* Returns the filter function of PROCESS; nil if none.
937See `set-process-filter' for more info on filter functions. */)
5842a27b 938 (register Lisp_Object process)
d0d6b7c5 939{
b7826503 940 CHECK_PROCESS (process);
4ee3e309 941 return XPROCESS (process)->filter;
d0d6b7c5
JB
942}
943
944DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
fdb82f93
PJ
945 2, 2, 0,
946 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
947The sentinel is called as a function when the process changes state.
948It gets two arguments: the process, and a string describing the change. */)
5842a27b 949 (register Lisp_Object process, Lisp_Object sentinel)
d0d6b7c5 950{
6b61353c
KH
951 struct Lisp_Process *p;
952
b7826503 953 CHECK_PROCESS (process);
6b61353c
KH
954 p = XPROCESS (process);
955
956 p->sentinel = sentinel;
d888760c 957 if (NETCONN1_P (p) || SERIALCONN1_P (p))
6b61353c 958 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
d0d6b7c5
JB
959 return sentinel;
960}
961
962DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
fdb82f93
PJ
963 1, 1, 0,
964 doc: /* Return the sentinel of PROCESS; nil if none.
965See `set-process-sentinel' for more info on sentinels. */)
5842a27b 966 (register Lisp_Object process)
d0d6b7c5 967{
b7826503 968 CHECK_PROCESS (process);
4ee3e309 969 return XPROCESS (process)->sentinel;
d0d6b7c5
JB
970}
971
396df322 972DEFUN ("set-process-window-size", Fset_process_window_size,
fdb82f93
PJ
973 Sset_process_window_size, 3, 3, 0,
974 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
5842a27b 975 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
396df322 976{
b7826503
PJ
977 CHECK_PROCESS (process);
978 CHECK_NATNUM (height);
979 CHECK_NATNUM (width);
177c0ea7 980
60f0fb11
SM
981 if (XPROCESS (process)->infd < 0
982 || set_window_size (XPROCESS (process)->infd,
471f86b9 983 XINT (height), XINT (width)) <= 0)
396df322
RS
984 return Qnil;
985 else
986 return Qt;
987}
988
52a1b894 989DEFUN ("set-process-inherit-coding-system-flag",
fdb82f93
PJ
990 Fset_process_inherit_coding_system_flag,
991 Sset_process_inherit_coding_system_flag, 2, 2, 0,
992 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
993If the second argument FLAG is non-nil, then the variable
994`buffer-file-coding-system' of the buffer associated with PROCESS
995will be bound to the value of the coding system used to decode
996the process output.
997
998This is useful when the coding system specified for the process buffer
999leaves either the character code conversion or the end-of-line conversion
1000unspecified, or if the coding system used to decode the process output
1001is more appropriate for saving the process buffer.
1002
1003Binding the variable `inherit-process-coding-system' to non-nil before
1004starting the process is an alternative way of setting the inherit flag
1005for the process which will run. */)
5842a27b 1006 (register Lisp_Object process, Lisp_Object flag)
52a1b894 1007{
b7826503 1008 CHECK_PROCESS (process);
60f0fb11 1009 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
52a1b894
EZ
1010 return flag;
1011}
1012
e690ca94
KS
1013DEFUN ("set-process-query-on-exit-flag",
1014 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1015 2, 2, 0,
1016 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
f3d9532b 1017If the second argument FLAG is non-nil, Emacs will query the user before
10be7e0d 1018exiting or killing a buffer if PROCESS is running. */)
5842a27b 1019 (register Lisp_Object process, Lisp_Object flag)
d0d6b7c5 1020{
b7826503 1021 CHECK_PROCESS (process);
60f0fb11 1022 XPROCESS (process)->kill_without_query = NILP (flag);
e690ca94 1023 return flag;
d0d6b7c5 1024}
312c9964 1025
e690ca94
KS
1026DEFUN ("process-query-on-exit-flag",
1027 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
fdb82f93 1028 1, 1, 0,
f3d9532b 1029 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
5842a27b 1030 (register Lisp_Object process)
de282a05 1031{
b7826503 1032 CHECK_PROCESS (process);
60f0fb11 1033 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
e690ca94
KS
1034}
1035
1036#ifdef DATAGRAM_SOCKETS
d3da34e0 1037Lisp_Object Fprocess_datagram_address (Lisp_Object process);
e690ca94
KS
1038#endif
1039
1040DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1041 1, 2, 0,
1042 doc: /* Return the contact info of PROCESS; t for a real child.
d888760c
GM
1043For a network or serial connection, the value depends on the optional
1044KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1045SERVICE) for a network connection or (PORT SPEED) for a serial
1046connection. If KEY is t, the complete contact information for the
1047connection is returned, else the specific value for the keyword KEY is
1048returned. See `make-network-process' or `make-serial-process' for a
1049list of keywords. */)
5842a27b 1050 (register Lisp_Object process, Lisp_Object key)
e690ca94
KS
1051{
1052 Lisp_Object contact;
1053
1054 CHECK_PROCESS (process);
1055 contact = XPROCESS (process)->childp;
1056
1057#ifdef DATAGRAM_SOCKETS
1058 if (DATAGRAM_CONN_P (process)
1059 && (EQ (key, Qt) || EQ (key, QCremote)))
177c0ea7 1060 contact = Fplist_put (contact, QCremote,
e690ca94
KS
1061 Fprocess_datagram_address (process));
1062#endif
1063
d888760c 1064 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
e690ca94 1065 return contact;
d888760c 1066 if (NILP (key) && NETCONN_P (process))
e690ca94
KS
1067 return Fcons (Fplist_get (contact, QChost),
1068 Fcons (Fplist_get (contact, QCservice), Qnil));
d888760c
GM
1069 if (NILP (key) && SERIALCONN_P (process))
1070 return Fcons (Fplist_get (contact, QCport),
1071 Fcons (Fplist_get (contact, QCspeed), Qnil));
e690ca94 1072 return Fplist_get (contact, key);
de282a05
RS
1073}
1074
faa7db08
KS
1075DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1076 1, 1, 0,
1077 doc: /* Return the plist of PROCESS. */)
5842a27b 1078 (register Lisp_Object process)
365aee82 1079{
ac4a7584 1080 CHECK_PROCESS (process);
faa7db08 1081 return XPROCESS (process)->plist;
ac4a7584 1082}
365aee82 1083
faa7db08
KS
1084DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1085 2, 2, 0,
26a086c6 1086 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
5842a27b 1087 (register Lisp_Object process, Lisp_Object plist)
ac4a7584 1088{
365aee82 1089 CHECK_PROCESS (process);
faa7db08 1090 CHECK_LIST (plist);
365aee82 1091
faa7db08 1092 XPROCESS (process)->plist = plist;
26a086c6 1093 return plist;
365aee82
KS
1094}
1095
312c9964
RS
1096#if 0 /* Turned off because we don't currently record this info
1097 in the process. Perhaps add it. */
1098DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
fdb82f93
PJ
1099 doc: /* Return the connection type of PROCESS.
1100The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1101a socket connection. */)
5842a27b 1102 (Lisp_Object process)
312c9964
RS
1103{
1104 return XPROCESS (process)->type;
1105}
1106#endif
2a7bb882 1107
d888760c
GM
1108DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1109 doc: /* Return the connection type of PROCESS.
1110The value is either the symbol `real', `network', or `serial'.
1111PROCESS may be a process, a buffer, the name of a process or buffer, or
1112nil, indicating the current buffer's process. */)
5842a27b 1113 (Lisp_Object process)
d888760c
GM
1114{
1115 Lisp_Object proc;
1116 proc = get_process (process);
1117 return XPROCESS (proc)->type;
1118}
991234f0 1119
991234f0 1120DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
0dccee41 1121 1, 2, 0,
991234f0 1122 doc: /* Convert network ADDRESS from internal format to a string.
e1652a86
KS
1123A 4 or 5 element vector represents an IPv4 address (with port number).
1124An 8 or 9 element vector represents an IPv6 address (with port number).
0dccee41 1125If optional second argument OMIT-PORT is non-nil, don't include a port
e1652a86
KS
1126number in the string, even when present in ADDRESS.
1127Returns nil if format of ADDRESS is invalid. */)
5842a27b 1128 (Lisp_Object address, Lisp_Object omit_port)
991234f0 1129{
991234f0
KS
1130 if (NILP (address))
1131 return Qnil;
1132
1133 if (STRINGP (address)) /* AF_LOCAL */
1134 return address;
1135
e1652a86 1136 if (VECTORP (address)) /* AF_INET or AF_INET6 */
991234f0
KS
1137 {
1138 register struct Lisp_Vector *p = XVECTOR (address);
ded83665 1139 Lisp_Object args[10];
0dccee41 1140 int nargs, i;
991234f0 1141
e1652a86 1142 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
0dccee41
KS
1143 {
1144 args[0] = build_string ("%d.%d.%d.%d");
1145 nargs = 4;
1146 }
1147 else if (p->size == 5)
1148 {
1149 args[0] = build_string ("%d.%d.%d.%d:%d");
1150 nargs = 5;
1151 }
e1652a86
KS
1152 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1153 {
1154 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1155 nargs = 8;
1156 }
1157 else if (p->size == 9)
1158 {
1159 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1160 nargs = 9;
1161 }
0dccee41 1162 else
991234f0
KS
1163 return Qnil;
1164
0dccee41 1165 for (i = 0; i < nargs; i++)
cbf23adb
JB
1166 {
1167 EMACS_INT element = XINT (p->contents[i]);
1168
1169 if (element < 0 || element > 65535)
1170 return Qnil;
1171
1172 if (nargs <= 5 /* IPv4 */
1173 && i < 4 /* host, not port */
1174 && element > 255)
1175 return Qnil;
1176
1177 args[i+1] = p->contents[i];
1178 }
1179
0dccee41 1180 return Fformat (nargs+1, args);
991234f0
KS
1181 }
1182
1183 if (CONSP (address))
1184 {
1185 Lisp_Object args[2];
1186 args[0] = build_string ("<Family %d>");
8d2ff840 1187 args[1] = Fcar (address);
991234f0 1188 return Fformat (2, args);
991234f0
KS
1189 }
1190
1191 return Qnil;
1192}
d0d6b7c5 1193\f
ff6daed3 1194static Lisp_Object
d3da34e0 1195list_processes_1 (Lisp_Object query_only)
d0d6b7c5
JB
1196{
1197 register Lisp_Object tail, tem;
1198 Lisp_Object proc, minspace, tem1;
d0d6b7c5 1199 register struct Lisp_Process *p;
e690ca94
KS
1200 char tembuf[300];
1201 int w_proc, w_buffer, w_tty;
1eed3bdc 1202 int exited = 0;
e690ca94
KS
1203 Lisp_Object i_status, i_buffer, i_tty, i_command;
1204
1205 w_proc = 4; /* Proc */
1206 w_buffer = 6; /* Buffer */
1207 w_tty = 0; /* Omit if no ttys */
1208
99784d63 1209 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
e690ca94
KS
1210 {
1211 int i;
1212
99784d63 1213 proc = Fcdr (XCAR (tail));
e690ca94 1214 p = XPROCESS (proc);
d888760c 1215 if (NILP (p->type))
e690ca94 1216 continue;
60f0fb11 1217 if (!NILP (query_only) && p->kill_without_query)
e690ca94
KS
1218 continue;
1219 if (STRINGP (p->name)
d5db4077 1220 && ( i = SCHARS (p->name), (i > w_proc)))
e690ca94
KS
1221 w_proc = i;
1222 if (!NILP (p->buffer))
1223 {
e69c4cae
SM
1224 if (NILP (XBUFFER (p->buffer)->name))
1225 {
1226 if (w_buffer < 8)
1227 w_buffer = 8; /* (Killed) */
1228 }
d5db4077 1229 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
e690ca94
KS
1230 w_buffer = i;
1231 }
1232 if (STRINGP (p->tty_name)
d5db4077 1233 && (i = SCHARS (p->tty_name), (i > w_tty)))
e690ca94
KS
1234 w_tty = i;
1235 }
1236
1237 XSETFASTINT (i_status, w_proc + 1);
1238 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1239 if (w_tty)
1240 {
1241 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
d3c0009d
AS
1242 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1243 }
1244 else
1245 {
e690ca94
KS
1246 i_tty = Qnil;
1247 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1248 }
d0d6b7c5 1249
22719df2 1250 XSETFASTINT (minspace, 1);
d0d6b7c5
JB
1251
1252 set_buffer_internal (XBUFFER (Vstandard_output));
ec2258fa 1253 current_buffer->undo_list = Qt;
d0d6b7c5
JB
1254
1255 current_buffer->truncate_lines = Qt;
1256
e690ca94
KS
1257 write_string ("Proc", -1);
1258 Findent_to (i_status, minspace); write_string ("Status", -1);
1259 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1260 if (!NILP (i_tty))
1261 {
1262 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1263 }
1264 Findent_to (i_command, minspace); write_string ("Command", -1);
1265 write_string ("\n", -1);
1266
1267 write_string ("----", -1);
1268 Findent_to (i_status, minspace); write_string ("------", -1);
1269 Findent_to (i_buffer, minspace); write_string ("------", -1);
1270 if (!NILP (i_tty))
1271 {
1272 Findent_to (i_tty, minspace); write_string ("---", -1);
1273 }
1274 Findent_to (i_command, minspace); write_string ("-------", -1);
1275 write_string ("\n", -1);
d0d6b7c5 1276
99784d63 1277 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
d0d6b7c5
JB
1278 {
1279 Lisp_Object symbol;
1280
99784d63 1281 proc = Fcdr (XCAR (tail));
d0d6b7c5 1282 p = XPROCESS (proc);
d888760c 1283 if (NILP (p->type))
d0d6b7c5 1284 continue;
60f0fb11 1285 if (!NILP (query_only) && p->kill_without_query)
e690ca94 1286 continue;
d0d6b7c5
JB
1287
1288 Finsert (1, &p->name);
e690ca94 1289 Findent_to (i_status, minspace);
d0d6b7c5 1290
6bfd98e7 1291 if (p->raw_status_new)
d0d6b7c5
JB
1292 update_status (p);
1293 symbol = p->status;
bcd69aea 1294 if (CONSP (p->status))
70949dac 1295 symbol = XCAR (p->status);
d0d6b7c5 1296
d0d6b7c5
JB
1297 if (EQ (symbol, Qsignal))
1298 {
1299 Lisp_Object tem;
1300 tem = Fcar (Fcdr (p->status));
7c2fb837 1301 Fprinc (symbol, Qnil);
d0d6b7c5 1302 }
d888760c 1303 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
d0d6b7c5 1304 {
e690ca94 1305 if (EQ (symbol, Qexit))
d0d6b7c5 1306 write_string ("closed", -1);
e690ca94
KS
1307 else if (EQ (p->command, Qt))
1308 write_string ("stopped", -1);
1309 else if (EQ (symbol, Qrun))
1310 write_string ("open", -1);
d0d6b7c5
JB
1311 else
1312 Fprinc (symbol, Qnil);
1313 }
d888760c
GM
1314 else if (SERIALCONN1_P (p))
1315 {
1316 write_string ("running", -1);
1317 }
d0d6b7c5
JB
1318 else
1319 Fprinc (symbol, Qnil);
1320
1321 if (EQ (symbol, Qexit))
1322 {
1323 Lisp_Object tem;
1324 tem = Fcar (Fcdr (p->status));
1325 if (XFASTINT (tem))
1326 {
3162bafa 1327 sprintf (tembuf, " %d", (int) XFASTINT (tem));
d0d6b7c5
JB
1328 write_string (tembuf, -1);
1329 }
1330 }
1331
1eed3bdc
KS
1332 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1333 exited++;
d0d6b7c5 1334
e690ca94 1335 Findent_to (i_buffer, minspace);
d0d6b7c5
JB
1336 if (NILP (p->buffer))
1337 insert_string ("(none)");
1338 else if (NILP (XBUFFER (p->buffer)->name))
1339 insert_string ("(Killed)");
1340 else
1341 Finsert (1, &XBUFFER (p->buffer)->name);
1342
e690ca94
KS
1343 if (!NILP (i_tty))
1344 {
1345 Findent_to (i_tty, minspace);
1346 if (STRINGP (p->tty_name))
1347 Finsert (1, &p->tty_name);
1348 }
a9fde32e 1349
e690ca94 1350 Findent_to (i_command, minspace);
a9fde32e 1351
e690ca94
KS
1352 if (EQ (p->status, Qlisten))
1353 {
1354 Lisp_Object port = Fplist_get (p->childp, QCservice);
1355 if (INTEGERP (port))
1356 port = Fnumber_to_string (port);
991234f0 1357 if (NILP (port))
0dccee41 1358 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
e690ca94 1359 sprintf (tembuf, "(network %s server on %s)\n",
60f0fb11 1360 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
991234f0 1361 (STRINGP (port) ? (char *)SDATA (port) : "?"));
e690ca94
KS
1362 insert_string (tembuf);
1363 }
1364 else if (NETCONN1_P (p))
63136da6 1365 {
e690ca94
KS
1366 /* For a local socket, there is no host name,
1367 so display service instead. */
1368 Lisp_Object host = Fplist_get (p->childp, QChost);
1369 if (!STRINGP (host))
1370 {
1371 host = Fplist_get (p->childp, QCservice);
1372 if (INTEGERP (host))
1373 host = Fnumber_to_string (host);
1374 }
991234f0 1375 if (NILP (host))
0dccee41 1376 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
e690ca94 1377 sprintf (tembuf, "(network %s connection to %s)\n",
60f0fb11 1378 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
991234f0 1379 (STRINGP (host) ? (char *)SDATA (host) : "?"));
d0d6b7c5 1380 insert_string (tembuf);
63136da6 1381 }
d888760c
GM
1382 else if (SERIALCONN1_P (p))
1383 {
1384 Lisp_Object port = Fplist_get (p->childp, QCport);
1385 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1386 insert_string ("(serial port ");
1387 if (STRINGP (port))
1388 insert_string (SDATA (port));
1389 else
1390 insert_string ("?");
1391 if (INTEGERP (speed))
1392 {
fa24b114 1393 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
d888760c
GM
1394 insert_string (tembuf);
1395 }
1396 insert_string (")\n");
1397 }
177c0ea7 1398 else
d0d6b7c5
JB
1399 {
1400 tem = p->command;
1401 while (1)
1402 {
1403 tem1 = Fcar (tem);
850d0752
NR
1404 if (NILP (tem1))
1405 break;
d0d6b7c5
JB
1406 Finsert (1, &tem1);
1407 tem = Fcdr (tem);
1408 if (NILP (tem))
1409 break;
1410 insert_string (" ");
1411 }
1412 insert_string ("\n");
1413 }
1414 }
1eed3bdc 1415 if (exited)
e42bdf01
CY
1416 {
1417 status_notify (NULL);
1418 redisplay_preserve_echo_area (13);
1419 }
d0d6b7c5
JB
1420 return Qnil;
1421}
1422
e690ca94 1423DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
fdb82f93 1424 doc: /* Display a list of all processes.
e690ca94
KS
1425If optional argument QUERY-ONLY is non-nil, only processes with
1426the query-on-exit flag set will be listed.
fdb82f93
PJ
1427Any process listed as exited or signaled is actually eliminated
1428after the listing is made. */)
5842a27b 1429 (Lisp_Object query_only)
d0d6b7c5
JB
1430{
1431 internal_with_output_to_temp_buffer ("*Process List*",
e690ca94 1432 list_processes_1, query_only);
d0d6b7c5
JB
1433 return Qnil;
1434}
1435
1436DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
fdb82f93 1437 doc: /* Return a list of all processes. */)
5842a27b 1438 (void)
d0d6b7c5
JB
1439{
1440 return Fmapcar (Qcdr, Vprocess_alist);
1441}
1442\f
b0310da4
JB
1443/* Starting asynchronous inferior processes. */
1444
d3da34e0 1445static Lisp_Object start_process_unwind (Lisp_Object proc);
b0310da4 1446
d0d6b7c5 1447DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
fdb82f93
PJ
1448 doc: /* Start a program in a subprocess. Return the process object for it.
1449NAME is name for process. It is modified if necessary to make it unique.
553acde5 1450BUFFER is the buffer (or buffer name) to associate with the process.
4b6c5eee
EZ
1451
1452Process output (both standard output and standard error streams) goes
1453at end of BUFFER, unless you specify an output stream or filter
1454function to handle the output. BUFFER may also be nil, meaning that
16fdeb17
RS
1455this process is not associated with any buffer.
1456
850d0752
NR
1457PROGRAM is the program file name. It is searched for in PATH. If
1458nil, just associate a pty with the buffer. Remaining arguments are
1459strings to give program as arguments.
320aebc9 1460
4b6c5eee
EZ
1461If you want to separate standard output from standard error, invoke
1462the command through a shell and redirect one of them using the shell
1463syntax.
320aebc9 1464
3ecdf100 1465usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
5842a27b 1466 (int nargs, register Lisp_Object *args)
d0d6b7c5 1467{
1e30af70 1468 Lisp_Object buffer, name, program, proc, current_dir, tem;
d0d6b7c5 1469 register unsigned char **new_argv;
d0d6b7c5 1470 register int i;
aed13378 1471 int count = SPECPDL_INDEX ();
d0d6b7c5
JB
1472
1473 buffer = args[1];
1474 if (!NILP (buffer))
1475 buffer = Fget_buffer_create (buffer);
1476
1e30af70
JB
1477 /* Make sure that the child will be able to chdir to the current
1478 buffer's current directory, or its unhandled equivalent. We
1479 can't just have the child check for an error when it does the
1480 chdir, since it's in a vfork.
1481
1482 We have to GCPRO around this because Fexpand_file_name and
1483 Funhandled_file_name_directory might call a file name handling
1484 function. The argument list is protected by the caller, so all
1485 we really have to worry about is buffer. */
1486 {
1487 struct gcpro gcpro1, gcpro2;
1488
1489 current_dir = current_buffer->directory;
1490
1491 GCPRO2 (buffer, current_dir);
1492
ca319910
SM
1493 current_dir = Funhandled_file_name_directory (current_dir);
1494 if (NILP (current_dir))
1495 /* If the file name handler says that current_dir is unreachable, use
1496 a sensible default. */
1497 current_dir = build_string ("~/");
1498 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1e30af70
JB
1499 if (NILP (Ffile_accessible_directory_p (current_dir)))
1500 report_file_error ("Setting current directory",
1501 Fcons (current_buffer->directory, Qnil));
1502
1503 UNGCPRO;
1504 }
1505
d0d6b7c5 1506 name = args[0];
b7826503 1507 CHECK_STRING (name);
d0d6b7c5
JB
1508
1509 program = args[2];
1510
850d0752
NR
1511 if (!NILP (program))
1512 CHECK_STRING (program);
d0d6b7c5 1513
d0d6b7c5 1514 proc = make_process (name);
b0310da4
JB
1515 /* If an error occurs and we can't start the process, we want to
1516 remove it from the process list. This means that each error
1517 check in create_process doesn't need to call remove_process
1518 itself; it's all taken care of here. */
1519 record_unwind_protect (start_process_unwind, proc);
d0d6b7c5
JB
1520
1521 XPROCESS (proc)->childp = Qt;
faa7db08 1522 XPROCESS (proc)->plist = Qnil;
d888760c 1523 XPROCESS (proc)->type = Qreal;
d0d6b7c5
JB
1524 XPROCESS (proc)->buffer = buffer;
1525 XPROCESS (proc)->sentinel = Qnil;
1526 XPROCESS (proc)->filter = Qnil;
1527 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1528
6b61353c 1529#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11
SM
1530 XPROCESS (proc)->adaptive_read_buffering
1531 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1532 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
6b61353c
KH
1533#endif
1534
7af71e17 1535 /* Make the process marker point into the process buffer (if any). */
f523e0c3 1536 if (BUFFERP (buffer))
d8a2934e
RS
1537 set_marker_both (XPROCESS (proc)->mark, buffer,
1538 BUF_ZV (XBUFFER (buffer)),
1539 BUF_ZV_BYTE (XBUFFER (buffer)));
7af71e17 1540
67918941 1541 {
d5d4ae71
KH
1542 /* Decide coding systems for communicating with the process. Here
1543 we don't setup the structure coding_system nor pay attention to
1544 unibyte mode. They are done in create_process. */
1545
67918941
RS
1546 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1547 Lisp_Object coding_systems = Qt;
1548 Lisp_Object val, *args2;
a4a37e65 1549 struct gcpro gcpro1, gcpro2;
67918941 1550
d5d4ae71
KH
1551 val = Vcoding_system_for_read;
1552 if (NILP (val))
67918941
RS
1553 {
1554 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1555 args2[0] = Qstart_process;
1556 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
a4a37e65 1557 GCPRO2 (proc, current_dir);
850d0752
NR
1558 if (!NILP (program))
1559 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
67918941
RS
1560 UNGCPRO;
1561 if (CONSP (coding_systems))
70949dac 1562 val = XCAR (coding_systems);
67918941 1563 else if (CONSP (Vdefault_process_coding_system))
70949dac 1564 val = XCAR (Vdefault_process_coding_system);
67918941
RS
1565 }
1566 XPROCESS (proc)->decode_coding_system = val;
1567
d5d4ae71
KH
1568 val = Vcoding_system_for_write;
1569 if (NILP (val))
67918941
RS
1570 {
1571 if (EQ (coding_systems, Qt))
1572 {
1573 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1574 args2[0] = Qstart_process;
1575 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
a4a37e65 1576 GCPRO2 (proc, current_dir);
850d0752
NR
1577 if (!NILP (program))
1578 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
67918941
RS
1579 UNGCPRO;
1580 }
1581 if (CONSP (coding_systems))
70949dac 1582 val = XCDR (coding_systems);
67918941 1583 else if (CONSP (Vdefault_process_coding_system))
70949dac 1584 val = XCDR (Vdefault_process_coding_system);
67918941
RS
1585 }
1586 XPROCESS (proc)->encode_coding_system = val;
1587 }
0fa1789e 1588
a4a37e65 1589
850d0752
NR
1590 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1591 XPROCESS (proc)->decoding_carryover = 0;
1592 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
ed30cf85 1593
850d0752
NR
1594 XPROCESS (proc)->inherit_coding_system_flag
1595 = !(NILP (buffer) || !inherit_process_coding_system);
77bf07e1 1596
850d0752
NR
1597 if (!NILP (program))
1598 {
1599 /* If program file name is not absolute, search our path for it.
1600 Put the name we will really use in TEM. */
1601 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1602 && !(SCHARS (program) > 1
1603 && IS_DEVICE_SEP (SREF (program, 1))))
1604 {
1605 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1606
1607 tem = Qnil;
1608 GCPRO4 (name, program, buffer, current_dir);
1609 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1610 UNGCPRO;
1611 if (NILP (tem))
1612 report_file_error ("Searching for program", Fcons (program, Qnil));
1613 tem = Fexpand_file_name (tem, Qnil);
1614 }
1615 else
1616 {
1617 if (!NILP (Ffile_directory_p (program)))
1618 error ("Specified program for new process is a directory");
1619 tem = program;
1620 }
ed30cf85 1621
850d0752
NR
1622 /* If program file name starts with /: for quoting a magic name,
1623 discard that. */
1624 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1625 && SREF (tem, 1) == ':')
1626 tem = Fsubstring (tem, make_number (2), Qnil);
77bf07e1 1627
77bf07e1 1628 {
850d0752
NR
1629 struct gcpro gcpro1;
1630 GCPRO1 (tem);
a4a37e65 1631
850d0752
NR
1632 /* Encode the file name and put it in NEW_ARGV.
1633 That's where the child will use it to execute the program. */
1634 tem = Fcons (ENCODE_FILE (tem), Qnil);
77bf07e1 1635
850d0752
NR
1636 /* Here we encode arguments by the coding system used for sending
1637 data to the process. We don't support using different coding
1638 systems for encoding arguments and for encoding data sent to the
1639 process. */
77bf07e1 1640
850d0752
NR
1641 for (i = 3; i < nargs; i++)
1642 {
1643 tem = Fcons (args[i], tem);
1644 CHECK_STRING (XCAR (tem));
1645 if (STRING_MULTIBYTE (XCAR (tem)))
1646 XSETCAR (tem,
1647 code_convert_string_norecord
1648 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1649 }
a4a37e65 1650
850d0752
NR
1651 UNGCPRO;
1652 }
0fa1789e 1653
850d0752
NR
1654 /* Now that everything is encoded we can collect the strings into
1655 NEW_ARGV. */
1656 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1657 new_argv[nargs - 2] = 0;
52a1b894 1658
850d0752
NR
1659 for (i = nargs - 3; i >= 0; i--)
1660 {
1661 new_argv[i] = SDATA (XCAR (tem));
1662 tem = XCDR (tem);
1663 }
1664
1665 create_process (proc, (char **) new_argv, current_dir);
1666 }
1667 else
1668 create_pty (proc);
d0d6b7c5 1669
b0310da4 1670 return unbind_to (count, proc);
d0d6b7c5
JB
1671}
1672
b0310da4 1673/* This function is the unwind_protect form for Fstart_process. If
8e6208c5 1674 PROC doesn't have its pid set, then we know someone has signaled
b0310da4
JB
1675 an error and the process wasn't started successfully, so we should
1676 remove it from the process list. */
1677static Lisp_Object
d3da34e0 1678start_process_unwind (Lisp_Object proc)
b0310da4 1679{
bcd69aea 1680 if (!PROCESSP (proc))
b0310da4
JB
1681 abort ();
1682
1683 /* Was PROC started successfully? */
850d0752 1684 if (XPROCESS (proc)->pid == -1)
b0310da4
JB
1685 remove_process (proc);
1686
1687 return Qnil;
1688}
1689
ff6daed3 1690static void
d3da34e0 1691create_process_1 (struct atimer *timer)
d0d6b7c5 1692{
30904ab7 1693 /* Nothing to do. */
d0d6b7c5
JB
1694}
1695
30904ab7 1696
6b53bb85 1697void
d3da34e0 1698create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
d0d6b7c5 1699{
29ed4d51
CY
1700 int inchannel, outchannel;
1701 pid_t pid;
d0d6b7c5 1702 int sv[2];
2c4df143
YM
1703#if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1704 int wait_child_setup[2];
1705#endif
0dc70c33
KH
1706 sigset_t procmask;
1707 sigset_t blocked;
1708 struct sigaction sigint_action;
1709 struct sigaction sigquit_action;
1710#ifdef AIX
1711 struct sigaction sighup_action;
1712#endif
ecd1f654
KH
1713 /* Use volatile to protect variables from being clobbered by longjmp. */
1714 volatile int forkin, forkout;
1715 volatile int pty_flag = 0;
3ec68006 1716#ifndef USE_CRT_DLL
d0d6b7c5 1717 extern char **environ;
3ec68006 1718#endif
d0d6b7c5 1719
d0d6b7c5
JB
1720 inchannel = outchannel = -1;
1721
1722#ifdef HAVE_PTYS
fe45da4e 1723 if (!NILP (Vprocess_connection_type))
d0d6b7c5
JB
1724 outchannel = inchannel = allocate_pty ();
1725
d0d6b7c5
JB
1726 if (inchannel >= 0)
1727 {
2af70a0c
RS
1728#if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1729 /* On most USG systems it does not work to open the pty's tty here,
1730 then close it and reopen it in the child. */
d0d6b7c5
JB
1731#ifdef O_NOCTTY
1732 /* Don't let this terminal become our controlling terminal
1733 (in case we don't have one). */
68c45bf0 1734 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
d0d6b7c5 1735#else
68c45bf0 1736 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
d0d6b7c5
JB
1737#endif
1738 if (forkin < 0)
1739 report_file_error ("Opening pty", Qnil);
1740#else
1741 forkin = forkout = -1;
2af70a0c 1742#endif /* not USG, or USG_SUBTTY_WORKS */
d0d6b7c5
JB
1743 pty_flag = 1;
1744 }
1745 else
1746#endif /* HAVE_PTYS */
d0d6b7c5 1747 {
fc14013c
KH
1748 int tem;
1749 tem = pipe (sv);
1750 if (tem < 0)
1751 report_file_error ("Creating pipe", Qnil);
d0d6b7c5
JB
1752 inchannel = sv[0];
1753 forkout = sv[1];
fc14013c
KH
1754 tem = pipe (sv);
1755 if (tem < 0)
1756 {
68c45bf0
PE
1757 emacs_close (inchannel);
1758 emacs_close (forkout);
fc14013c
KH
1759 report_file_error ("Creating pipe", Qnil);
1760 }
d0d6b7c5
JB
1761 outchannel = sv[1];
1762 forkin = sv[0];
1763 }
d0d6b7c5 1764
2c4df143
YM
1765#if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1766 {
1767 int tem;
1768
1769 tem = pipe (wait_child_setup);
1770 if (tem < 0)
1771 report_file_error ("Creating pipe", Qnil);
1772 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1773 if (tem >= 0)
1774 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1775 if (tem < 0)
1776 {
1777 emacs_close (wait_child_setup[0]);
1778 emacs_close (wait_child_setup[1]);
1779 report_file_error ("Setting file descriptor flags", Qnil);
1780 }
1781 }
1782#endif
1783
d0d6b7c5
JB
1784#if 0
1785 /* Replaced by close_process_descs */
1786 set_exclusive_use (inchannel);
1787 set_exclusive_use (outchannel);
1788#endif
1789
d0d6b7c5
JB
1790#ifdef O_NONBLOCK
1791 fcntl (inchannel, F_SETFL, O_NONBLOCK);
03832893 1792 fcntl (outchannel, F_SETFL, O_NONBLOCK);
d0d6b7c5
JB
1793#else
1794#ifdef O_NDELAY
1795 fcntl (inchannel, F_SETFL, O_NDELAY);
03832893 1796 fcntl (outchannel, F_SETFL, O_NDELAY);
d0d6b7c5
JB
1797#endif
1798#endif
1799
1800 /* Record this as an active process, with its channels.
1801 As a result, child_setup will close Emacs's side of the pipes. */
1802 chan_process[inchannel] = process;
60f0fb11
SM
1803 XPROCESS (process)->infd = inchannel;
1804 XPROCESS (process)->outfd = outchannel;
16782258
JD
1805
1806 /* Previously we recorded the tty descriptor used in the subprocess.
1807 It was only used for getting the foreground tty process, so now
1808 we just reopen the device (see emacs_get_tty_pgrp) as this is
1809 more portable (see USG_SUBTTY_WORKS above). */
1810
60f0fb11 1811 XPROCESS (process)->pty_flag = pty_flag;
d0d6b7c5 1812 XPROCESS (process)->status = Qrun;
03f04413 1813 setup_process_coding_systems (process);
d0d6b7c5
JB
1814
1815 /* Delay interrupts until we have a chance to store
1816 the new fork's pid in its process structure */
0dc70c33
KH
1817 sigemptyset (&blocked);
1818#ifdef SIGCHLD
1819 sigaddset (&blocked, SIGCHLD);
1820#endif
351e611f 1821#ifdef HAVE_WORKING_VFORK
0dc70c33
KH
1822 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1823 this sets the parent's signal handlers as well as the child's.
1824 So delay all interrupts whose handlers the child might munge,
1825 and record the current handlers so they can be restored later. */
1826 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1827 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1828#ifdef AIX
1829 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1830#endif
351e611f 1831#endif /* HAVE_WORKING_VFORK */
0dc70c33 1832 sigprocmask (SIG_BLOCK, &blocked, &procmask);
d0d6b7c5 1833
3081bf8d 1834 FD_SET (inchannel, &input_wait_mask);
a69281ff 1835 FD_SET (inchannel, &non_keyboard_wait_mask);
3081bf8d
KH
1836 if (inchannel > max_process_desc)
1837 max_process_desc = inchannel;
1838
d0d6b7c5
JB
1839 /* Until we store the proper pid, enable sigchld_handler
1840 to recognize an unknown pid as standing for this process.
1841 It is very important not to let this `marker' value stay
1842 in the table after this function has returned; if it does
1843 it might cause call-process to hang and subsequent asynchronous
1844 processes to get their return values scrambled. */
6bfd98e7 1845 XPROCESS (process)->pid = -1;
d0d6b7c5 1846
ececcbec 1847 BLOCK_INPUT;
177c0ea7 1848
d0d6b7c5
JB
1849 {
1850 /* child_setup must clobber environ on systems with true vfork.
1851 Protect it from permanent change. */
1852 char **save_environ = environ;
1853
14dc6093 1854 current_dir = ENCODE_FILE (current_dir);
a932f187 1855
e98d950b 1856#ifndef WINDOWSNT
d0d6b7c5
JB
1857 pid = vfork ();
1858 if (pid == 0)
e98d950b 1859#endif /* not WINDOWSNT */
d0d6b7c5
JB
1860 {
1861 int xforkin = forkin;
1862 int xforkout = forkout;
1863
1864#if 0 /* This was probably a mistake--it duplicates code later on,
1865 but fails to handle all the cases. */
1866 /* Make sure SIGCHLD is not blocked in the child. */
1867 sigsetmask (SIGEMPTYMASK);
1868#endif
1869
1870 /* Make the pty be the controlling terminal of the process. */
1871#ifdef HAVE_PTYS
1872 /* First, disconnect its current controlling terminal. */
1873#ifdef HAVE_SETSID
7ce48618
RS
1874 /* We tried doing setsid only if pty_flag, but it caused
1875 process_set_signal to fail on SGI when using a pipe. */
1876 setsid ();
ce4c9c90 1877 /* Make the pty's terminal the controlling terminal. */
ce8f5a9a 1878 if (pty_flag && xforkin >= 0)
39e9ebcd 1879 {
39e9ebcd
RS
1880#ifdef TIOCSCTTY
1881 /* We ignore the return value
1882 because faith@cs.unc.edu says that is necessary on Linux. */
1883 ioctl (xforkin, TIOCSCTTY, 0);
ce4c9c90 1884#endif
39e9ebcd 1885 }
d0d6b7c5 1886#else /* not HAVE_SETSID */
c14e53a4 1887#ifdef USG
000ab717 1888 /* It's very important to call setpgrp here and no time
d0d6b7c5
JB
1889 afterwards. Otherwise, we lose our controlling tty which
1890 is set when we open the pty. */
1891 setpgrp ();
1892#endif /* USG */
1893#endif /* not HAVE_SETSID */
a7ebc409 1894#if defined (LDISC1)
9bcf8ec6
KH
1895 if (pty_flag && xforkin >= 0)
1896 {
1897 struct termios t;
1898 tcgetattr (xforkin, &t);
1899 t.c_lflag = LDISC1;
1900 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
68c45bf0 1901 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
9bcf8ec6
KH
1902 }
1903#else
aafadd9f 1904#if defined (NTTYDISC) && defined (TIOCSETD)
ff773a4e 1905 if (pty_flag && xforkin >= 0)
afc549fd
RS
1906 {
1907 /* Use new line discipline. */
1908 int ldisc = NTTYDISC;
4458f555 1909 ioctl (xforkin, TIOCSETD, &ldisc);
afc549fd 1910 }
000ab717 1911#endif
9bcf8ec6 1912#endif
177c0ea7 1913#ifdef TIOCNOTTY
d0d6b7c5
JB
1914 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1915 can do TIOCSPGRP only to the process's controlling tty. */
1916 if (pty_flag)
1917 {
177c0ea7 1918 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
d0d6b7c5 1919 I can't test it since I don't have 4.3. */
68c45bf0 1920 int j = emacs_open ("/dev/tty", O_RDWR, 0);
ce8f5a9a
AS
1921 if (j >= 0)
1922 {
1923 ioctl (j, TIOCNOTTY, 0);
1924 emacs_close (j);
1925 }
5a570e37 1926#ifndef USG
d0d6b7c5
JB
1927 /* In order to get a controlling terminal on some versions
1928 of BSD, it is necessary to put the process in pgrp 0
1929 before it opens the terminal. */
99c1aeca 1930#ifdef HAVE_SETPGID
3ea1d291
RS
1931 setpgid (0, 0);
1932#else
d0d6b7c5 1933 setpgrp (0, 0);
3ea1d291 1934#endif
d0d6b7c5
JB
1935#endif
1936 }
1937#endif /* TIOCNOTTY */
1938
e39a993c 1939#if !defined (DONT_REOPEN_PTY)
d0d6b7c5 1940/*** There is a suggestion that this ought to be a
99153b9e
RS
1941 conditional on TIOCSPGRP,
1942 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1943 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1944 that system does seem to need this code, even though
1945 both HAVE_SETSID and TIOCSCTTY are defined. */
d0d6b7c5
JB
1946 /* Now close the pty (if we had it open) and reopen it.
1947 This makes the pty the controlling terminal of the subprocess. */
1948 if (pty_flag)
1949 {
99e3d726 1950
68c45bf0
PE
1951 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1952 would work? */
d0d6b7c5 1953 if (xforkin >= 0)
68c45bf0
PE
1954 emacs_close (xforkin);
1955 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
d0d6b7c5 1956
4aa54ba8
RS
1957 if (xforkin < 0)
1958 {
68c45bf0
PE
1959 emacs_write (1, "Couldn't open the pty terminal ", 31);
1960 emacs_write (1, pty_name, strlen (pty_name));
1961 emacs_write (1, "\n", 1);
4aa54ba8
RS
1962 _exit (1);
1963 }
1964
d0d6b7c5 1965 }
e39a993c 1966#endif /* not DONT_REOPEN_PTY */
e9bf058b 1967
d0d6b7c5 1968#ifdef SETUP_SLAVE_PTY
13a72104
RS
1969 if (pty_flag)
1970 {
1971 SETUP_SLAVE_PTY;
1972 }
d0d6b7c5
JB
1973#endif /* SETUP_SLAVE_PTY */
1974#ifdef AIX
1975 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1976 Now reenable it in the child, so it will die when we want it to. */
1977 if (pty_flag)
1978 signal (SIGHUP, SIG_DFL);
1979#endif
1980#endif /* HAVE_PTYS */
1981
0dc70c33
KH
1982 signal (SIGINT, SIG_DFL);
1983 signal (SIGQUIT, SIG_DFL);
1984
1985 /* Stop blocking signals in the child. */
0dc70c33 1986 sigprocmask (SIG_SETMASK, &procmask, 0);
5e7e1da2 1987
ab01d0a8
RS
1988 if (pty_flag)
1989 child_setup_tty (xforkout);
e98d950b
RS
1990#ifdef WINDOWSNT
1991 pid = child_setup (xforkin, xforkout, xforkout,
1992 new_argv, 1, current_dir);
177c0ea7 1993#else /* not WINDOWSNT */
2c4df143
YM
1994#ifdef FD_CLOEXEC
1995 emacs_close (wait_child_setup[0]);
1996#endif
d0d6b7c5 1997 child_setup (xforkin, xforkout, xforkout,
e065a56e 1998 new_argv, 1, current_dir);
e98d950b 1999#endif /* not WINDOWSNT */
d0d6b7c5
JB
2000 }
2001 environ = save_environ;
2002 }
2003
ececcbec
RS
2004 UNBLOCK_INPUT;
2005
4a127b3b 2006 /* This runs in the Emacs process. */
d0d6b7c5 2007 if (pid < 0)
6311cf58
RS
2008 {
2009 if (forkin >= 0)
68c45bf0 2010 emacs_close (forkin);
6311cf58 2011 if (forkin != forkout && forkout >= 0)
68c45bf0 2012 emacs_close (forkout);
6311cf58 2013 }
4a127b3b
KH
2014 else
2015 {
2016 /* vfork succeeded. */
6bfd98e7 2017 XPROCESS (process)->pid = pid;
d0d6b7c5 2018
e98d950b 2019#ifdef WINDOWSNT
4a127b3b 2020 register_child (pid, inchannel);
e98d950b
RS
2021#endif /* WINDOWSNT */
2022
4a127b3b
KH
2023 /* If the subfork execv fails, and it exits,
2024 this close hangs. I don't know why.
2025 So have an interrupt jar it loose. */
30904ab7
GM
2026 {
2027 struct atimer *timer;
2028 EMACS_TIME offset;
177c0ea7 2029
30904ab7
GM
2030 stop_polling ();
2031 EMACS_SET_SECS_USECS (offset, 1, 0);
2032 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
177c0ea7 2033
30904ab7
GM
2034 if (forkin >= 0)
2035 emacs_close (forkin);
2036
2037 cancel_atimer (timer);
2038 start_polling ();
2039 }
177c0ea7 2040
4a127b3b 2041 if (forkin != forkout && forkout >= 0)
68c45bf0 2042 emacs_close (forkout);
d0d6b7c5 2043
875e6b94 2044#ifdef HAVE_PTYS
4a127b3b
KH
2045 if (pty_flag)
2046 XPROCESS (process)->tty_name = build_string (pty_name);
2047 else
875e6b94 2048#endif
4a127b3b 2049 XPROCESS (process)->tty_name = Qnil;
2c4df143
YM
2050
2051#if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2052 /* Wait for child_setup to complete in case that vfork is
2053 actually defined as fork. The descriptor wait_child_setup[1]
2054 of a pipe is closed at the child side either by close-on-exec
2055 on successful execvp or the _exit call in child_setup. */
2056 {
2057 char dummy;
2058
2059 emacs_close (wait_child_setup[1]);
2060 emacs_read (wait_child_setup[0], &dummy, 1);
2061 emacs_close (wait_child_setup[0]);
2062 }
2063#endif
4a127b3b 2064 }
3b9a3dfa 2065
4a127b3b
KH
2066 /* Restore the signal state whether vfork succeeded or not.
2067 (We will signal an error, below, if it failed.) */
351e611f 2068#ifdef HAVE_WORKING_VFORK
0dc70c33
KH
2069 /* Restore the parent's signal handlers. */
2070 sigaction (SIGINT, &sigint_action, 0);
2071 sigaction (SIGQUIT, &sigquit_action, 0);
2072#ifdef AIX
2073 sigaction (SIGHUP, &sighup_action, 0);
2074#endif
351e611f 2075#endif /* HAVE_WORKING_VFORK */
0dc70c33
KH
2076 /* Stop blocking signals in the parent. */
2077 sigprocmask (SIG_SETMASK, &procmask, 0);
4a127b3b
KH
2078
2079 /* Now generate the error if vfork failed. */
2080 if (pid < 0)
2081 report_file_error ("Doing vfork", Qnil);
d0d6b7c5 2082}
d0d6b7c5 2083
850d0752 2084void
d3da34e0 2085create_pty (Lisp_Object process)
850d0752
NR
2086{
2087 int inchannel, outchannel;
2088
2089 /* Use volatile to protect variables from being clobbered by longjmp. */
2090 volatile int forkin, forkout;
2091 volatile int pty_flag = 0;
2092
2093 inchannel = outchannel = -1;
2094
2095#ifdef HAVE_PTYS
2096 if (!NILP (Vprocess_connection_type))
2097 outchannel = inchannel = allocate_pty ();
2098
2099 if (inchannel >= 0)
2100 {
2101#if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2102 /* On most USG systems it does not work to open the pty's tty here,
2103 then close it and reopen it in the child. */
2104#ifdef O_NOCTTY
2105 /* Don't let this terminal become our controlling terminal
2106 (in case we don't have one). */
2107 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2108#else
2109 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2110#endif
2111 if (forkin < 0)
2112 report_file_error ("Opening pty", Qnil);
019d2c4c 2113#if defined (DONT_REOPEN_PTY)
850d0752
NR
2114 /* In the case that vfork is defined as fork, the parent process
2115 (Emacs) may send some data before the child process completes
2116 tty options setup. So we setup tty before forking. */
2117 child_setup_tty (forkout);
019d2c4c 2118#endif /* DONT_REOPEN_PTY */
850d0752
NR
2119#else
2120 forkin = forkout = -1;
2121#endif /* not USG, or USG_SUBTTY_WORKS */
2122 pty_flag = 1;
2123 }
2124#endif /* HAVE_PTYS */
2125
2126#ifdef O_NONBLOCK
2127 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2128 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2129#else
2130#ifdef O_NDELAY
2131 fcntl (inchannel, F_SETFL, O_NDELAY);
2132 fcntl (outchannel, F_SETFL, O_NDELAY);
2133#endif
2134#endif
2135
2136 /* Record this as an active process, with its channels.
2137 As a result, child_setup will close Emacs's side of the pipes. */
2138 chan_process[inchannel] = process;
2139 XPROCESS (process)->infd = inchannel;
2140 XPROCESS (process)->outfd = outchannel;
2141
2142 /* Previously we recorded the tty descriptor used in the subprocess.
2143 It was only used for getting the foreground tty process, so now
2144 we just reopen the device (see emacs_get_tty_pgrp) as this is
2145 more portable (see USG_SUBTTY_WORKS above). */
2146
2147 XPROCESS (process)->pty_flag = pty_flag;
2148 XPROCESS (process)->status = Qrun;
2149 setup_process_coding_systems (process);
2150
2151 FD_SET (inchannel, &input_wait_mask);
2152 FD_SET (inchannel, &non_keyboard_wait_mask);
2153 if (inchannel > max_process_desc)
2154 max_process_desc = inchannel;
2155
2156 XPROCESS (process)->pid = -2;
8b9fc636
EZ
2157#ifdef HAVE_PTYS
2158 if (pty_flag)
2159 XPROCESS (process)->tty_name = build_string (pty_name);
2160 else
2161#endif
2162 XPROCESS (process)->tty_name = Qnil;
850d0752
NR
2163}
2164
e690ca94 2165\f
e690ca94
KS
2166/* Convert an internal struct sockaddr to a lisp object (vector or string).
2167 The address family of sa is not included in the result. */
2168
2169static Lisp_Object
d3da34e0 2170conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
e690ca94
KS
2171{
2172 Lisp_Object address;
2173 int i;
2174 unsigned char *cp;
2175 register struct Lisp_Vector *p;
2176
63136da6
AS
2177 /* Workaround for a bug in getsockname on BSD: Names bound to
2178 sockets in the UNIX domain are inaccessible; getsockname returns
2179 a zero length name. */
89887d67 2180 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
fff4e459 2181 return empty_unibyte_string;
63136da6 2182
e690ca94
KS
2183 switch (sa->sa_family)
2184 {
2185 case AF_INET:
2186 {
2187 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2188 len = sizeof (sin->sin_addr) + 1;
2189 address = Fmake_vector (make_number (len), Qnil);
2190 p = XVECTOR (address);
2191 p->contents[--len] = make_number (ntohs (sin->sin_port));
63136da6 2192 cp = (unsigned char *) &sin->sin_addr;
e690ca94
KS
2193 break;
2194 }
e1652a86
KS
2195#ifdef AF_INET6
2196 case AF_INET6:
2197 {
2198 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
63136da6 2199 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
e1652a86
KS
2200 len = sizeof (sin6->sin6_addr)/2 + 1;
2201 address = Fmake_vector (make_number (len), Qnil);
2202 p = XVECTOR (address);
2203 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2204 for (i = 0; i < len; i++)
2205 p->contents[i] = make_number (ntohs (ip6[i]));
2206 return address;
2207 }
2208#endif
e690ca94
KS
2209#ifdef HAVE_LOCAL_SOCKETS
2210 case AF_LOCAL:
2211 {
fb23673a
EZ
2212 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2213 for (i = 0; i < sizeof (sockun->sun_path); i++)
2214 if (sockun->sun_path[i] == 0)
e690ca94 2215 break;
fb23673a 2216 return make_unibyte_string (sockun->sun_path, i);
e690ca94
KS
2217 }
2218#endif
2219 default:
89887d67 2220 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
e690ca94
KS
2221 address = Fcons (make_number (sa->sa_family),
2222 Fmake_vector (make_number (len), Qnil));
2223 p = XVECTOR (XCDR (address));
63136da6 2224 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
e690ca94
KS
2225 break;
2226 }
2227
2228 i = 0;
2229 while (i < len)
2230 p->contents[i++] = make_number (*cp++);
2231
2232 return address;
2233}
2234
2235
2236/* Get family and required size for sockaddr structure to hold ADDRESS. */
2237
2238static int
d3da34e0 2239get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
e690ca94
KS
2240{
2241 register struct Lisp_Vector *p;
2242
2243 if (VECTORP (address))
2244 {
2245 p = XVECTOR (address);
2246 if (p->size == 5)
2247 {
2248 *familyp = AF_INET;
2249 return sizeof (struct sockaddr_in);
2250 }
e1652a86
KS
2251#ifdef AF_INET6
2252 else if (p->size == 9)
2253 {
2254 *familyp = AF_INET6;
2255 return sizeof (struct sockaddr_in6);
2256 }
2257#endif
e690ca94
KS
2258 }
2259#ifdef HAVE_LOCAL_SOCKETS
2260 else if (STRINGP (address))
2261 {
2262 *familyp = AF_LOCAL;
2263 return sizeof (struct sockaddr_un);
2264 }
2265#endif
2266 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2267 {
2268 struct sockaddr *sa;
2269 *familyp = XINT (XCAR (address));
2270 p = XVECTOR (XCDR (address));
2271 return p->size + sizeof (sa->sa_family);
2272 }
2273 return 0;
2274}
2275
2276/* Convert an address object (vector or string) to an internal sockaddr.
9d1a8e5d
RS
2277
2278 The address format has been basically validated by
2279 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2280 it could have come from user data. So if FAMILY is not valid,
2281 we return after zeroing *SA. */
e690ca94
KS
2282
2283static void
d3da34e0 2284conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
e690ca94
KS
2285{
2286 register struct Lisp_Vector *p;
34967d0f 2287 register unsigned char *cp = NULL;
e690ca94
KS
2288 register int i;
2289
72af86bd 2290 memset (sa, 0, len);
e690ca94
KS
2291
2292 if (VECTORP (address))
2293 {
2294 p = XVECTOR (address);
2295 if (family == AF_INET)
2296 {
2297 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2298 len = sizeof (sin->sin_addr) + 1;
2299 i = XINT (p->contents[--len]);
2300 sin->sin_port = htons (i);
2301 cp = (unsigned char *)&sin->sin_addr;
9d1a8e5d 2302 sa->sa_family = family;
e690ca94 2303 }
e1652a86
KS
2304#ifdef AF_INET6
2305 else if (family == AF_INET6)
2306 {
2307 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2308 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2309 len = sizeof (sin6->sin6_addr) + 1;
2310 i = XINT (p->contents[--len]);
2311 sin6->sin6_port = htons (i);
2312 for (i = 0; i < len; i++)
2313 if (INTEGERP (p->contents[i]))
2314 {
2315 int j = XFASTINT (p->contents[i]) & 0xffff;
2316 ip6[i] = ntohs (j);
2317 }
9d1a8e5d 2318 sa->sa_family = family;
0eb7675e 2319 return;
e1652a86
KS
2320 }
2321#endif
0eb7675e
AS
2322 else
2323 return;
e690ca94
KS
2324 }
2325 else if (STRINGP (address))
2326 {
2327#ifdef HAVE_LOCAL_SOCKETS
2328 if (family == AF_LOCAL)
2329 {
fb23673a 2330 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
d5db4077 2331 cp = SDATA (address);
fb23673a
EZ
2332 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2333 sockun->sun_path[i] = *cp++;
9d1a8e5d 2334 sa->sa_family = family;
e690ca94
KS
2335 }
2336#endif
2337 return;
2338 }
2339 else
2340 {
2341 p = XVECTOR (XCDR (address));
2342 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2343 }
2344
2345 for (i = 0; i < len; i++)
2346 if (INTEGERP (p->contents[i]))
2347 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2348}
2349
2350#ifdef DATAGRAM_SOCKETS
2351DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2352 1, 1, 0,
2353 doc: /* Get the current datagram address associated with PROCESS. */)
5842a27b 2354 (Lisp_Object process)
e690ca94
KS
2355{
2356 int channel;
2357
2358 CHECK_PROCESS (process);
2359
2360 if (!DATAGRAM_CONN_P (process))
2361 return Qnil;
2362
60f0fb11 2363 channel = XPROCESS (process)->infd;
e690ca94
KS
2364 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2365 datagram_address[channel].len);
2366}
2367
2368DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2369 2, 2, 0,
2370 doc: /* Set the datagram address for PROCESS to ADDRESS.
2371Returns nil upon error setting address, ADDRESS otherwise. */)
5842a27b 2372 (Lisp_Object process, Lisp_Object address)
e690ca94
KS
2373{
2374 int channel;
2375 int family, len;
2376
2377 CHECK_PROCESS (process);
2378
2379 if (!DATAGRAM_CONN_P (process))
2380 return Qnil;
2381
60f0fb11 2382 channel = XPROCESS (process)->infd;
e690ca94
KS
2383
2384 len = get_lisp_to_sockaddr_size (address, &family);
2385 if (datagram_address[channel].len != len)
2386 return Qnil;
2387 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2388 return address;
2389}
2390#endif
2391\f
2392
5e2327cf 2393static const struct socket_options {
e690ca94 2394 /* The name of this option. Should be lowercase version of option
177c0ea7 2395 name without SO_ prefix. */
fce70521 2396 const char *name;
e690ca94
KS
2397 /* Option level SOL_... */
2398 int optlevel;
2399 /* Option number SO_... */
2400 int optnum;
6b61353c
KH
2401 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2402 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
e690ca94
KS
2403} socket_options[] =
2404 {
2405#ifdef SO_BINDTODEVICE
6b61353c 2406 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
e690ca94
KS
2407#endif
2408#ifdef SO_BROADCAST
6b61353c 2409 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
e690ca94
KS
2410#endif
2411#ifdef SO_DONTROUTE
6b61353c 2412 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
e690ca94
KS
2413#endif
2414#ifdef SO_KEEPALIVE
6b61353c 2415 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
e690ca94
KS
2416#endif
2417#ifdef SO_LINGER
6b61353c 2418 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
e690ca94
KS
2419#endif
2420#ifdef SO_OOBINLINE
6b61353c 2421 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
e690ca94
KS
2422#endif
2423#ifdef SO_PRIORITY
6b61353c 2424 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
e690ca94
KS
2425#endif
2426#ifdef SO_REUSEADDR
6b61353c 2427 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
e690ca94 2428#endif
6b61353c 2429 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
e690ca94
KS
2430 };
2431
6b61353c 2432/* Set option OPT to value VAL on socket S.
e690ca94 2433
6b61353c
KH
2434 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2435 Signals an error if setting a known option fails.
2436*/
e690ca94
KS
2437
2438static int
d3da34e0 2439set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
e690ca94 2440{
6b61353c 2441 char *name;
5e2327cf 2442 const struct socket_options *sopt;
6b61353c 2443 int ret = 0;
e690ca94 2444
6b61353c 2445 CHECK_SYMBOL (opt);
e690ca94 2446
6b61353c
KH
2447 name = (char *) SDATA (SYMBOL_NAME (opt));
2448 for (sopt = socket_options; sopt->name; sopt++)
2449 if (strcmp (name, sopt->name) == 0)
2450 break;
e690ca94 2451
6b61353c
KH
2452 switch (sopt->opttype)
2453 {
2454 case SOPT_BOOL:
2455 {
2456 int optval;
2457 optval = NILP (val) ? 0 : 1;
2458 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2459 &optval, sizeof (optval));
2460 break;
2461 }
e690ca94 2462
6b61353c
KH
2463 case SOPT_INT:
2464 {
2465 int optval;
2466 if (INTEGERP (val))
2467 optval = XINT (val);
2468 else
2469 error ("Bad option value for %s", name);
2470 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2471 &optval, sizeof (optval));
2472 break;
2473 }
e690ca94 2474
6b61353c
KH
2475#ifdef SO_BINDTODEVICE
2476 case SOPT_IFNAME:
2477 {
2478 char devname[IFNAMSIZ+1];
e690ca94 2479
6b61353c
KH
2480 /* This is broken, at least in the Linux 2.4 kernel.
2481 To unbind, the arg must be a zero integer, not the empty string.
2482 This should work on all systems. KFS. 2003-09-23. */
72af86bd 2483 memset (devname, 0, sizeof devname);
6b61353c 2484 if (STRINGP (val))
e690ca94 2485 {
6b61353c
KH
2486 char *arg = (char *) SDATA (val);
2487 int len = min (strlen (arg), IFNAMSIZ);
72af86bd 2488 memcpy (devname, arg, len);
e690ca94 2489 }
6b61353c
KH
2490 else if (!NILP (val))
2491 error ("Bad option value for %s", name);
2492 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2493 devname, IFNAMSIZ);
2494 break;
2495 }
2496#endif
e690ca94 2497
177c0ea7 2498#ifdef SO_LINGER
6b61353c
KH
2499 case SOPT_LINGER:
2500 {
2501 struct linger linger;
e690ca94 2502
6b61353c
KH
2503 linger.l_onoff = 1;
2504 linger.l_linger = 0;
2505 if (INTEGERP (val))
2506 linger.l_linger = XINT (val);
2507 else
2508 linger.l_onoff = NILP (val) ? 0 : 1;
2509 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2510 &linger, sizeof (linger));
2511 break;
2512 }
e690ca94 2513#endif
6b61353c
KH
2514
2515 default:
2516 return 0;
e690ca94 2517 }
6b61353c
KH
2518
2519 if (ret < 0)
2520 report_file_error ("Cannot set network option",
2521 Fcons (opt, Fcons (val, Qnil)));
2522 return (1 << sopt->optbit);
e690ca94
KS
2523}
2524
6b61353c
KH
2525
2526DEFUN ("set-network-process-option",
2527 Fset_network_process_option, Sset_network_process_option,
2528 3, 4, 0,
2529 doc: /* For network process PROCESS set option OPTION to value VALUE.
2530See `make-network-process' for a list of options and values.
2531If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2532OPTION is not a supported option, return nil instead; otherwise return t. */)
5842a27b 2533 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
e690ca94 2534{
6b61353c
KH
2535 int s;
2536 struct Lisp_Process *p;
e690ca94 2537
e690ca94 2538 CHECK_PROCESS (process);
6b61353c
KH
2539 p = XPROCESS (process);
2540 if (!NETCONN1_P (p))
2541 error ("Process is not a network process");
2542
60f0fb11 2543 s = p->infd;
6b61353c
KH
2544 if (s < 0)
2545 error ("Process is not running");
2546
2547 if (set_socket_option (s, option, value))
e690ca94 2548 {
6b61353c
KH
2549 p->childp = Fplist_put (p->childp, option, value);
2550 return Qt;
e690ca94 2551 }
6b61353c
KH
2552
2553 if (NILP (no_error))
2554 error ("Unknown or unsupported option");
2555
2556 return Qnil;
e690ca94 2557}
6b61353c 2558
e690ca94 2559\f
d888760c
GM
2560DEFUN ("serial-process-configure",
2561 Fserial_process_configure,
2562 Sserial_process_configure,
2563 0, MANY, 0,
2564 doc: /* Configure speed, bytesize, etc. of a serial process.
2565
2566Arguments are specified as keyword/argument pairs. Attributes that
2567are not given are re-initialized from the process's current
2568configuration (available via the function `process-contact') or set to
2569reasonable default values. The following arguments are defined:
2570
2571:process PROCESS
2572:name NAME
2573:buffer BUFFER
2574:port PORT
2575-- Any of these arguments can be given to identify the process that is
2576to be configured. If none of these arguments is given, the current
2577buffer's process is used.
2578
2579:speed SPEED -- SPEED is the speed of the serial port in bits per
2580second, also called baud rate. Any value can be given for SPEED, but
2581most serial ports work only at a few defined values between 1200 and
2582115200, with 9600 being the most common value. If SPEED is nil, the
2583serial port is not configured any further, i.e., all other arguments
2584are ignored. This may be useful for special serial ports such as
2585Bluetooth-to-serial converters which can only be configured through AT
2586commands. A value of nil for SPEED can be used only when passed
2587through `make-serial-process' or `serial-term'.
2588
2589:bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2590can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2591
2592:parity PARITY -- PARITY can be nil (don't use parity), the symbol
2593`odd' (use odd parity), or the symbol `even' (use even parity). If
2594PARITY is not given, no parity is used.
2595
2596:stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2597terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2598is not given or nil, 1 stopbit is used.
2599
2600:flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2601flowcontrol to be used, which is either nil (don't use flowcontrol),
2602the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2603\(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2604flowcontrol is used.
2605
2606`serial-process-configure' is called by `make-serial-process' for the
2607initial configuration of the serial port.
2608
2609Examples:
2610
2611\(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2612
2613\(serial-process-configure
2614 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2615
2616\(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2617
2618usage: (serial-process-configure &rest ARGS) */)
5842a27b 2619 (int nargs, Lisp_Object *args)
d888760c
GM
2620{
2621 struct Lisp_Process *p;
2622 Lisp_Object contact = Qnil;
2623 Lisp_Object proc = Qnil;
2624 struct gcpro gcpro1;
2625
2626 contact = Flist (nargs, args);
2627 GCPRO1 (contact);
2628
2629 proc = Fplist_get (contact, QCprocess);
2630 if (NILP (proc))
2631 proc = Fplist_get (contact, QCname);
2632 if (NILP (proc))
2633 proc = Fplist_get (contact, QCbuffer);
2634 if (NILP (proc))
2635 proc = Fplist_get (contact, QCport);
2636 proc = get_process (proc);
2637 p = XPROCESS (proc);
a879ee6f 2638 if (!EQ (p->type, Qserial))
d888760c
GM
2639 error ("Not a serial process");
2640
2641 if (NILP (Fplist_get (p->childp, QCspeed)))
2642 {
2643 UNGCPRO;
2644 return Qnil;
2645 }
2646
2647 serial_configure (p, contact);
2648
2649 UNGCPRO;
2650 return Qnil;
2651}
d888760c 2652
d888760c
GM
2653/* Used by make-serial-process to recover from errors. */
2654Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2655{
2656 if (!PROCESSP (proc))
2657 abort ();
2658 remove_process (proc);
2659 return Qnil;
2660}
d888760c 2661
d888760c
GM
2662DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2663 0, MANY, 0,
2664 doc: /* Create and return a serial port process.
2665
2666In Emacs, serial port connections are represented by process objects,
2667so input and output work as for subprocesses, and `delete-process'
2668closes a serial port connection. However, a serial process has no
2669process id, it cannot be signaled, and the status codes are different
2670from normal processes.
2671
2672`make-serial-process' creates a process and a buffer, on which you
2673probably want to use `process-send-string'. Try \\[serial-term] for
2674an interactive terminal. See below for examples.
2675
2676Arguments are specified as keyword/argument pairs. The following
2677arguments are defined:
2678
2679:port PORT -- (mandatory) PORT is the path or name of the serial port.
2680For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2681could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2682the backslashes in strings).
2683
2684:speed SPEED -- (mandatory) is handled by `serial-process-configure',
2685which is called by `make-serial-process'.
2686
2687:name NAME -- NAME is the name of the process. If NAME is not given,
2688the value of PORT is used.
2689
2690:buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2691with the process. Process output goes at the end of that buffer,
2692unless you specify an output stream or filter function to handle the
2693output. If BUFFER is not given, the value of NAME is used.
2694
2695:coding CODING -- If CODING is a symbol, it specifies the coding
2696system used for both reading and writing for this process. If CODING
2697is a cons (DECODING . ENCODING), DECODING is used for reading, and
2698ENCODING is used for writing.
2699
2700:noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2701the process is running. If BOOL is not given, query before exiting.
2702
2703:stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2704In the stopped state, a serial process does not accept incoming data,
2705but you can send outgoing data. The stopped state is cleared by
2706`continue-process' and set by `stop-process'.
2707
2708:filter FILTER -- Install FILTER as the process filter.
2709
2710:sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2711
2712:plist PLIST -- Install PLIST as the initial plist of the process.
2713
2714:speed
2715:bytesize
2716:parity
2717:stopbits
2718:flowcontrol
2719-- These arguments are handled by `serial-process-configure', which is
2720called by `make-serial-process'.
2721
2722The original argument list, possibly modified by later configuration,
2723is available via the function `process-contact'.
2724
2725Examples:
2726
2727\(make-serial-process :port "/dev/ttyS0" :speed 9600)
2728
2729\(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2730
2731\(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2732
2733\(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2734
2735usage: (make-serial-process &rest ARGS) */)
5842a27b 2736 (int nargs, Lisp_Object *args)
d888760c
GM
2737{
2738 int fd = -1;
2739 Lisp_Object proc, contact, port;
2740 struct Lisp_Process *p;
2741 struct gcpro gcpro1;
2742 Lisp_Object name, buffer;
2743 Lisp_Object tem, val;
2744 int specpdl_count = -1;
2745
2746 if (nargs == 0)
2747 return Qnil;
2748
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2751
2752 port = Fplist_get (contact, QCport);
2753 if (NILP (port))
2754 error ("No port specified");
2755 CHECK_STRING (port);
2756
2757 if (NILP (Fplist_member (contact, QCspeed)))
2758 error (":speed not specified");
2759 if (!NILP (Fplist_get (contact, QCspeed)))
2760 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2761
2762 name = Fplist_get (contact, QCname);
2763 if (NILP (name))
2764 name = port;
2765 CHECK_STRING (name);
2766 proc = make_process (name);
2767 specpdl_count = SPECPDL_INDEX ();
2768 record_unwind_protect (make_serial_process_unwind, proc);
2769 p = XPROCESS (proc);
2770
2771 fd = serial_open ((char*) SDATA (port));
2772 p->infd = fd;
2773 p->outfd = fd;
2774 if (fd > max_process_desc)
2775 max_process_desc = fd;
2776 chan_process[fd] = proc;
2777
2778 buffer = Fplist_get (contact, QCbuffer);
2779 if (NILP (buffer))
2780 buffer = name;
2781 buffer = Fget_buffer_create (buffer);
2782 p->buffer = buffer;
2783
2784 p->childp = contact;
2785 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2786 p->type = Qserial;
2787 p->sentinel = Fplist_get (contact, QCsentinel);
2788 p->filter = Fplist_get (contact, QCfilter);
2789 p->log = Qnil;
2790 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2791 p->kill_without_query = 1;
2792 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2793 p->command = Qt;
2794 p->pty_flag = 0;
2795
2796 if (!EQ (p->command, Qt))
2797 {
2798 FD_SET (fd, &input_wait_mask);
2799 FD_SET (fd, &non_keyboard_wait_mask);
2800 }
2801
2802 if (BUFFERP (buffer))
2803 {
2804 set_marker_both (p->mark, buffer,
2805 BUF_ZV (XBUFFER (buffer)),
2806 BUF_ZV_BYTE (XBUFFER (buffer)));
2807 }
2808
2809 tem = Fplist_member (contact, QCcoding);
2810 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2811 tem = Qnil;
2812
2813 val = Qnil;
2814 if (!NILP (tem))
2815 {
2816 val = XCAR (XCDR (tem));
2817 if (CONSP (val))
2818 val = XCAR (val);
2819 }
2820 else if (!NILP (Vcoding_system_for_read))
2821 val = Vcoding_system_for_read;
2822 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2823 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2824 val = Qnil;
2825 p->decode_coding_system = val;
2826
2827 val = Qnil;
2828 if (!NILP (tem))
2829 {
2830 val = XCAR (XCDR (tem));
2831 if (CONSP (val))
2832 val = XCDR (val);
2833 }
2834 else if (!NILP (Vcoding_system_for_write))
2835 val = Vcoding_system_for_write;
2836 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2837 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2838 val = Qnil;
2839 p->encode_coding_system = val;
2840
2841 setup_process_coding_systems (proc);
2842 p->decoding_buf = make_uninit_string (0);
2843 p->decoding_carryover = 0;
2844 p->encoding_buf = make_uninit_string (0);
2845 p->inherit_coding_system_flag
2846 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2847
ed3751c8 2848 Fserial_process_configure (nargs, args);
d888760c
GM
2849
2850 specpdl_ptr = specpdl + specpdl_count;
2851
2852 UNGCPRO;
2853 return proc;
2854}
d888760c 2855
e690ca94
KS
2856/* Create a network stream/datagram client/server process. Treated
2857 exactly like a normal process when reading and writing. Primary
d0d6b7c5
JB
2858 differences are in status display and process deletion. A network
2859 connection has no PID; you cannot signal it. All you can do is
e690ca94
KS
2860 stop/continue it and deactivate/close it via delete-process */
2861
177c0ea7
JB
2862DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2863 0, MANY, 0,
e690ca94
KS
2864 doc: /* Create and return a network server or client process.
2865
fa9d4315 2866In Emacs, network connections are represented by process objects, so
e690ca94
KS
2867input and output work as for subprocesses and `delete-process' closes
2868a network connection. However, a network process has no process id,
d22426e1 2869it cannot be signaled, and the status codes are different from normal
e690ca94
KS
2870processes.
2871
2872Arguments are specified as keyword/argument pairs. The following
2873arguments are defined:
2874
2875:name NAME -- NAME is name for process. It is modified if necessary
2876to make it unique.
2877
2878:buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2879with the process. Process output goes at end of that buffer, unless
2880you specify an output stream or filter function to handle the output.
2881BUFFER may be also nil, meaning that this process is not associated
2882with any buffer.
2883
2884:host HOST -- HOST is name of the host to connect to, or its IP
2885address. The symbol `local' specifies the local host. If specified
2886for a server process, it must be a valid name or address for the local
2887host, and only clients connecting to that address will be accepted.
2888
2889:service SERVICE -- SERVICE is name of the service desired, or an
2890integer specifying a port number to connect to. If SERVICE is t,
eba25e7c
GM
2891a random port number is selected for the server. (If Emacs was
2892compiled with getaddrinfo, a port number can also be specified as a
2893string, e.g. "80", as well as an integer. This is not portable.)
e690ca94 2894
9057ff80 2895:type TYPE -- TYPE is the type of connection. The default (nil) is a
f00c449b
SM
2896stream type connection, `datagram' creates a datagram type connection,
2897`seqpacket' creates a reliable datagram connection.
9057ff80 2898
e690ca94 2899:family FAMILY -- FAMILY is the address (and protocol) family for the
e1652a86
KS
2900service specified by HOST and SERVICE. The default (nil) is to use
2901whatever address family (IPv4 or IPv6) that is defined for the host
2902and port number specified by HOST and SERVICE. Other address families
2903supported are:
e690ca94 2904 local -- for a local (i.e. UNIX) address specified by SERVICE.
e1652a86
KS
2905 ipv4 -- use IPv4 address family only.
2906 ipv6 -- use IPv6 address family only.
e690ca94
KS
2907
2908:local ADDRESS -- ADDRESS is the local address used for the connection.
2909This parameter is ignored when opening a client process. When specified
2910for a server process, the FAMILY, HOST and SERVICE args are ignored.
2911
2912:remote ADDRESS -- ADDRESS is the remote partner's address for the
2913connection. This parameter is ignored when opening a stream server
2914process. For a datagram server process, it specifies the initial
2915setting of the remote datagram address. When specified for a client
2916process, the FAMILY, HOST, and SERVICE args are ignored.
2917
2918The format of ADDRESS depends on the address family:
2919- An IPv4 address is represented as an vector of integers [A B C D P]
2920corresponding to numeric IP address A.B.C.D and port number P.
2921- A local address is represented as a string with the address in the
2922local address space.
2923- An "unsupported family" address is represented by a cons (F . AV)
2924where F is the family number and AV is a vector containing the socket
2925address data with one element per address data byte. Do not rely on
2926this format in portable code, as it may depend on implementation
2927defined constants, data sizes, and data structure alignment.
2928
6b61353c
KH
2929:coding CODING -- If CODING is a symbol, it specifies the coding
2930system used for both reading and writing for this process. If CODING
2931is a cons (DECODING . ENCODING), DECODING is used for reading, and
2932ENCODING is used for writing.
e690ca94
KS
2933
2934:nowait BOOL -- If BOOL is non-nil for a stream type client process,
2935return without waiting for the connection to complete; instead, the
2936sentinel function will be called with second arg matching "open" (if
2937successful) or "failed" when the connect completes. Default is to use
2938a blocking connect (i.e. wait) for stream type connections.
2939
2940:noquery BOOL -- Query the user unless BOOL is non-nil, and process is
f3d9532b 2941running when Emacs is exited.
e690ca94
KS
2942
2943:stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2944In the stopped state, a server process does not accept new
2945connections, and a client process does not handle incoming traffic.
2946The stopped state is cleared by `continue-process' and set by
2947`stop-process'.
2948
2949:filter FILTER -- Install FILTER as the process filter.
2950
7392e23c
KS
2951:filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2952process filter are multibyte, otherwise they are unibyte.
e0f24100 2953If this keyword is not specified, the strings are multibyte if
03f04413
KH
2954`default-enable-multibyte-characters' is non-nil.
2955
e690ca94
KS
2956:sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2957
2958:log LOG -- Install LOG as the server process log function. This
991234f0 2959function is called when the server accepts a network connection from a
e690ca94
KS
2960client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2961is the server process, CLIENT is the new process for the connection,
2962and MESSAGE is a string.
2963
faa7db08 2964:plist PLIST -- Install PLIST as the new process' initial plist.
177c0ea7 2965
6b61353c 2966:server QLEN -- if QLEN is non-nil, create a server process for the
e690ca94 2967specified FAMILY, SERVICE, and connection type (stream or datagram).
6b61353c
KH
2968If QLEN is an integer, it is used as the max. length of the server's
2969pending connection queue (also known as the backlog); the default
2970queue length is 5. Default is to create a client process.
2971
2972The following network options can be specified for this connection:
2973
2974:broadcast BOOL -- Allow send and receive of datagram broadcasts.
2975:dontroute BOOL -- Only send to directly connected hosts.
2976:keepalive BOOL -- Send keep-alive messages on network stream.
2977:linger BOOL or TIMEOUT -- Send queued messages before closing.
2978:oobinline BOOL -- Place out-of-band data in receive data stream.
2979:priority INT -- Set protocol defined priority for sent packets.
2980:reuseaddr BOOL -- Allow reusing a recently used local address
2981 (this is allowed by default for a server process).
2982:bindtodevice NAME -- bind to interface NAME. Using this may require
2983 special privileges on some systems.
2984
2985Consult the relevant system programmer's manual pages for more
2986information on using these options.
2987
2988
2989A server process will listen for and accept connections from clients.
2990When a client connection is accepted, a new network process is created
2991for the connection with the following parameters:
e690ca94 2992
e690ca94
KS
2993- The client's process name is constructed by concatenating the server
2994process' NAME and a client identification string.
2995- If the FILTER argument is non-nil, the client process will not get a
2996separate process buffer; otherwise, the client's process buffer is a newly
2997created buffer named after the server process' BUFFER name or process
177c0ea7 2998NAME concatenated with the client identification string.
e690ca94
KS
2999- The connection type and the process filter and sentinel parameters are
3000inherited from the server process' TYPE, FILTER and SENTINEL.
3001- The client process' contact info is set according to the client's
3002addressing information (typically an IP address and a port number).
faa7db08 3003- The client process' plist is initialized from the server's plist.
e690ca94
KS
3004
3005Notice that the FILTER and SENTINEL args are never used directly by
3006the server process. Also, the BUFFER argument is not used directly by
9e9a5792
KS
3007the server process, but via the optional :log function, accepted (and
3008failed) connections may be logged in the server process' buffer.
e690ca94 3009
365aee82
KS
3010The original argument list, modified with the actual connection
3011information, is available via the `process-contact' function.
365aee82 3012
fa9d4315 3013usage: (make-network-process &rest ARGS) */)
5842a27b 3014 (int nargs, Lisp_Object *args)
d0d6b7c5
JB
3015{
3016 Lisp_Object proc;
e690ca94
KS
3017 Lisp_Object contact;
3018 struct Lisp_Process *p;
70dbdb36 3019#ifdef HAVE_GETADDRINFO
e690ca94 3020 struct addrinfo ai, *res, *lres;
e1652a86 3021 struct addrinfo hints;
8ea90aa3
DN
3022 const char *portstring;
3023 char portbuf[128];
70dbdb36 3024#else /* HAVE_GETADDRINFO */
dd2a17ab
KS
3025 struct _emacs_addrinfo
3026 {
3027 int ai_family;
3028 int ai_socktype;
3029 int ai_protocol;
3030 int ai_addrlen;
3031 struct sockaddr *ai_addr;
3032 struct _emacs_addrinfo *ai_next;
3033 } ai, *res, *lres;
418b48fd 3034#endif /* HAVE_GETADDRINFO */
e690ca94
KS
3035 struct sockaddr_in address_in;
3036#ifdef HAVE_LOCAL_SOCKETS
3037 struct sockaddr_un address_un;
3038#endif
3039 int port;
dd2a17ab
KS
3040 int ret = 0;
3041 int xerrno = 0;
418b48fd 3042 int s = -1, outch, inch;
e690ca94 3043 struct gcpro gcpro1;
aed13378 3044 int count = SPECPDL_INDEX ();
5684cd6e 3045 int count1;
e690ca94
KS
3046 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3047 Lisp_Object tem;
3048 Lisp_Object name, buffer, host, service, address;
3049 Lisp_Object filter, sentinel;
3050 int is_non_blocking_client = 0;
6b61353c 3051 int is_server = 0, backlog = 5;
9057ff80 3052 int socktype;
e690ca94
KS
3053 int family = -1;
3054
3055 if (nargs == 0)
3056 return Qnil;
dd2a17ab 3057
e690ca94
KS
3058 /* Save arguments for process-contact and clone-process. */
3059 contact = Flist (nargs, args);
3060 GCPRO1 (contact);
3061
bff3ed0a
RS
3062#ifdef WINDOWSNT
3063 /* Ensure socket support is loaded if available. */
3064 init_winsock (TRUE);
3065#endif
3066
9057ff80
KS
3067 /* :type TYPE (nil: stream, datagram */
3068 tem = Fplist_get (contact, QCtype);
3069 if (NILP (tem))
3070 socktype = SOCK_STREAM;
3071#ifdef DATAGRAM_SOCKETS
3072 else if (EQ (tem, Qdatagram))
3073 socktype = SOCK_DGRAM;
f00c449b
SM
3074#endif
3075#ifdef HAVE_SEQPACKET
3076 else if (EQ (tem, Qseqpacket))
3077 socktype = SOCK_SEQPACKET;
e690ca94 3078#endif
9057ff80
KS
3079 else
3080 error ("Unsupported connection type");
e690ca94
KS
3081
3082 /* :server BOOL */
3083 tem = Fplist_get (contact, QCserver);
3084 if (!NILP (tem))
3085 {
75728599
JR
3086 /* Don't support network sockets when non-blocking mode is
3087 not available, since a blocked Emacs is not useful. */
132d0475 3088#if !defined(O_NONBLOCK) && !defined(O_NDELAY)
e690ca94
KS
3089 error ("Network servers not supported");
3090#else
3091 is_server = 1;
6b61353c
KH
3092 if (INTEGERP (tem))
3093 backlog = XINT (tem);
e690ca94
KS
3094#endif
3095 }
3096
3097 /* Make QCaddress an alias for :local (server) or :remote (client). */
3098 QCaddress = is_server ? QClocal : QCremote;
3099
d7e344cd 3100 /* :nowait BOOL */
84b31826 3101 if (!is_server && socktype != SOCK_DGRAM
e690ca94
KS
3102 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3103 {
3104#ifndef NON_BLOCKING_CONNECT
3105 error ("Non-blocking connect not supported");
3106#else
3107 is_non_blocking_client = 1;
3108#endif
3109 }
3110
3111 name = Fplist_get (contact, QCname);
3112 buffer = Fplist_get (contact, QCbuffer);
3113 filter = Fplist_get (contact, QCfilter);
3114 sentinel = Fplist_get (contact, QCsentinel);
3115
b7826503 3116 CHECK_STRING (name);
e690ca94 3117
e690ca94
KS
3118 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3119 ai.ai_socktype = socktype;
3120 ai.ai_protocol = 0;
3121 ai.ai_next = NULL;
3122 res = &ai;
a319f7c1 3123
e690ca94
KS
3124 /* :local ADDRESS or :remote ADDRESS */
3125 address = Fplist_get (contact, QCaddress);
3126 if (!NILP (address))
a319f7c1 3127 {
e690ca94
KS
3128 host = service = Qnil;
3129
3130 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3131 error ("Malformed :address");
3132 ai.ai_family = family;
3133 ai.ai_addr = alloca (ai.ai_addrlen);
3134 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3135 goto open_socket;
a319f7c1 3136 }
e690ca94
KS
3137
3138 /* :family FAMILY -- nil (for Inet), local, or integer. */
3139 tem = Fplist_get (contact, QCfamily);
e1652a86 3140 if (NILP (tem))
a319f7c1 3141 {
87b6ca8d 3142#if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
e1652a86
KS
3143 family = AF_UNSPEC;
3144#else
3145 family = AF_INET;
e690ca94 3146#endif
a319f7c1 3147 }
e1652a86
KS
3148#ifdef HAVE_LOCAL_SOCKETS
3149 else if (EQ (tem, Qlocal))
3150 family = AF_LOCAL;
3151#endif
3152#ifdef AF_INET6
3153 else if (EQ (tem, Qipv6))
3154 family = AF_INET6;
3155#endif
3156 else if (EQ (tem, Qipv4))
3157 family = AF_INET;
3158 else if (INTEGERP (tem))
3159 family = XINT (tem);
3160 else
e690ca94 3161 error ("Unknown address family");
e1652a86 3162
e690ca94
KS
3163 ai.ai_family = family;
3164
3165 /* :service SERVICE -- string, integer (port number), or t (random port). */
3166 service = Fplist_get (contact, QCservice);
3167
66a9f7f4
SM
3168 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3169 host = Fplist_get (contact, QChost);
3170 if (!NILP (host))
3171 {
3172 if (EQ (host, Qlocal))
3173 host = build_string ("localhost");
3174 CHECK_STRING (host);
3175 }
3176
e690ca94
KS
3177#ifdef HAVE_LOCAL_SOCKETS
3178 if (family == AF_LOCAL)
d0d6b7c5 3179 {
66a9f7f4
SM
3180 if (!NILP (host))
3181 {
3182 message (":family local ignores the :host \"%s\" property",
3183 SDATA (host));
3184 contact = Fplist_put (contact, QChost, Qnil);
3185 host = Qnil;
3186 }
b7826503 3187 CHECK_STRING (service);
72af86bd 3188 memset (&address_un, 0, sizeof address_un);
e690ca94 3189 address_un.sun_family = AF_LOCAL;
d5db4077 3190 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
e690ca94
KS
3191 ai.ai_addr = (struct sockaddr *) &address_un;
3192 ai.ai_addrlen = sizeof address_un;
3193 goto open_socket;
d0d6b7c5 3194 }
e690ca94 3195#endif
a319f7c1 3196
798b64bb
KH
3197 /* Slow down polling to every ten seconds.
3198 Some kernels have a bug which causes retrying connect to fail
3199 after a connect. Polling can interfere with gethostbyname too. */
3200#ifdef POLL_FOR_INPUT
84b31826 3201 if (socktype != SOCK_DGRAM)
e690ca94
KS
3202 {
3203 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3204 bind_polling_period (10);
3205 }
798b64bb
KH
3206#endif
3207
a319f7c1 3208#ifdef HAVE_GETADDRINFO
e690ca94
KS
3209 /* If we have a host, use getaddrinfo to resolve both host and service.
3210 Otherwise, use getservbyname to lookup the service. */
3211 if (!NILP (host))
3212 {
3213
3214 /* SERVICE can either be a string or int.
3215 Convert to a C string for later use by getaddrinfo. */
3216 if (EQ (service, Qt))
3217 portstring = "0";
3218 else if (INTEGERP (service))
3219 {
3220 sprintf (portbuf, "%ld", (long) XINT (service));
3221 portstring = portbuf;
3222 }
3223 else
3224 {
3225 CHECK_STRING (service);
d5db4077 3226 portstring = SDATA (service);
e690ca94
KS
3227 }
3228
3229 immediate_quit = 1;
3230 QUIT;
3231 memset (&hints, 0, sizeof (hints));
3232 hints.ai_flags = 0;
e1652a86 3233 hints.ai_family = family;
e690ca94
KS
3234 hints.ai_socktype = socktype;
3235 hints.ai_protocol = 0;
08116b48
CY
3236
3237#ifdef HAVE_RES_INIT
3238 res_init ();
3239#endif
3240
d5db4077 3241 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
e690ca94 3242 if (ret)
f6270f62 3243#ifdef HAVE_GAI_STRERROR
ed3751c8 3244 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
f6270f62 3245#else
63136da6 3246 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
f6270f62 3247#endif
e690ca94 3248 immediate_quit = 0;
a319f7c1 3249
e690ca94
KS
3250 goto open_socket;
3251 }
3252#endif /* HAVE_GETADDRINFO */
a319f7c1 3253
e690ca94
KS
3254 /* We end up here if getaddrinfo is not defined, or in case no hostname
3255 has been specified (e.g. for a local server process). */
3256
3257 if (EQ (service, Qt))
3258 port = 0;
3259 else if (INTEGERP (service))
3260 port = htons ((unsigned short) XINT (service));
3261 else
616da37c 3262 {
e690ca94
KS
3263 struct servent *svc_info;
3264 CHECK_STRING (service);
177c0ea7 3265 svc_info = getservbyname (SDATA (service),
e690ca94
KS
3266 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3267 if (svc_info == 0)
d5db4077 3268 error ("Unknown service: %s", SDATA (service));
e690ca94
KS
3269 port = svc_info->s_port;
3270 }
3271
72af86bd 3272 memset (&address_in, 0, sizeof address_in);
e690ca94
KS
3273 address_in.sin_family = family;
3274 address_in.sin_addr.s_addr = INADDR_ANY;
3275 address_in.sin_port = port;
3276
3277#ifndef HAVE_GETADDRINFO
3278 if (!NILP (host))
3279 {
3280 struct hostent *host_info_ptr;
3281
3282 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
f3d9532b 3283 as it may `hang' Emacs for a very long time. */
5d6c2aa3
RS
3284 immediate_quit = 1;
3285 QUIT;
08116b48
CY
3286
3287#ifdef HAVE_RES_INIT
3288 res_init ();
3289#endif
3290
d5db4077 3291 host_info_ptr = gethostbyname (SDATA (host));
5d6c2aa3 3292 immediate_quit = 0;
177c0ea7 3293
e690ca94
KS
3294 if (host_info_ptr)
3295 {
72af86bd
AS
3296 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3297 host_info_ptr->h_length);
e690ca94
KS
3298 family = host_info_ptr->h_addrtype;
3299 address_in.sin_family = family;
3300 }
3301 else
3302 /* Attempt to interpret host as numeric inet address */
3303 {
4624371d 3304 unsigned long numeric_addr;
d5db4077 3305 numeric_addr = inet_addr ((char *) SDATA (host));
4624371d 3306 if (numeric_addr == -1)
d5db4077 3307 error ("Unknown host \"%s\"", SDATA (host));
d0d6b7c5 3308
72af86bd
AS
3309 memcpy (&address_in.sin_addr, &numeric_addr,
3310 sizeof (address_in.sin_addr));
e690ca94 3311 }
d0d6b7c5 3312
e690ca94 3313 }
dd2a17ab 3314#endif /* not HAVE_GETADDRINFO */
d0d6b7c5 3315
e690ca94
KS
3316 ai.ai_family = family;
3317 ai.ai_addr = (struct sockaddr *) &address_in;
3318 ai.ai_addrlen = sizeof address_in;
3319
3320 open_socket:
3321
dd2a17ab 3322 /* Do this in case we never enter the for-loop below. */
aed13378 3323 count1 = SPECPDL_INDEX ();
dd2a17ab 3324 s = -1;
457a9bee 3325
dd2a17ab
KS
3326 for (lres = res; lres; lres = lres->ai_next)
3327 {
6b61353c
KH
3328 int optn, optbits;
3329
649dbf36
CY
3330 retry_connect:
3331
dd2a17ab
KS
3332 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3333 if (s < 0)
3334 {
3335 xerrno = errno;
3336 continue;
3337 }
0f2ee0c1 3338
e690ca94
KS
3339#ifdef DATAGRAM_SOCKETS
3340 if (!is_server && socktype == SOCK_DGRAM)
3341 break;
3342#endif /* DATAGRAM_SOCKETS */
3343
dd2a17ab 3344#ifdef NON_BLOCKING_CONNECT
e690ca94 3345 if (is_non_blocking_client)
dd2a17ab
KS
3346 {
3347#ifdef O_NONBLOCK
3348 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3349#else
3350 ret = fcntl (s, F_SETFL, O_NDELAY);
3351#endif
3352 if (ret < 0)
3353 {
3354 xerrno = errno;
3355 emacs_close (s);
3356 s = -1;
3357 continue;
3358 }
3359 }
3360#endif
177c0ea7 3361
dd2a17ab 3362 /* Make us close S if quit. */
dd2a17ab
KS
3363 record_unwind_protect (close_file_unwind, make_number (s));
3364
6b61353c
KH
3365 /* Parse network options in the arg list.
3366 We simply ignore anything which isn't a known option (including other keywords).
63136da6 3367 An error is signaled if setting a known option fails. */
6b61353c
KH
3368 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3369 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3370
e690ca94
KS
3371 if (is_server)
3372 {
3373 /* Configure as a server socket. */
6b61353c
KH
3374
3375 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3376 explicit :reuseaddr key to override this. */
e690ca94
KS
3377#ifdef HAVE_LOCAL_SOCKETS
3378 if (family != AF_LOCAL)
3379#endif
6b61353c
KH
3380 if (!(optbits & (1 << OPIX_REUSEADDR)))
3381 {
3382 int optval = 1;
3383 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3384 report_file_error ("Cannot set reuse option on server socket", Qnil);
3385 }
177c0ea7 3386
e690ca94
KS
3387 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3388 report_file_error ("Cannot bind server socket", Qnil);
3389
3390#ifdef HAVE_GETSOCKNAME
3391 if (EQ (service, Qt))
3392 {
3393 struct sockaddr_in sa1;
3394 int len1 = sizeof (sa1);
3395 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3396 {
3397 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
21bd170d 3398 service = make_number (ntohs (sa1.sin_port));
e690ca94
KS
3399 contact = Fplist_put (contact, QCservice, service);
3400 }
3401 }
3402#endif
3403
84b31826 3404 if (socktype != SOCK_DGRAM && listen (s, backlog))
e690ca94
KS
3405 report_file_error ("Cannot listen on server socket", Qnil);
3406
3407 break;
3408 }
3409
dd2a17ab
KS
3410 immediate_quit = 1;
3411 QUIT;
3412
dd2a17ab
KS
3413 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3414 xerrno = errno;
3415
dd2a17ab
KS
3416 if (ret == 0 || xerrno == EISCONN)
3417 {
dd2a17ab
KS
3418 /* The unwind-protect will be discarded afterwards.
3419 Likewise for immediate_quit. */
3420 break;
3421 }
3422
3423#ifdef NON_BLOCKING_CONNECT
3424#ifdef EINPROGRESS
e690ca94 3425 if (is_non_blocking_client && xerrno == EINPROGRESS)
dd2a17ab
KS
3426 break;
3427#else
3428#ifdef EWOULDBLOCK
e690ca94 3429 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
dd2a17ab
KS
3430 break;
3431#endif
3432#endif
3433#endif
649dbf36
CY
3434
3435#ifndef WINDOWSNT
cd591dbc
HE
3436 if (xerrno == EINTR)
3437 {
3438 /* Unlike most other syscalls connect() cannot be called
3439 again. (That would return EALREADY.) The proper way to
3440 wait for completion is select(). */
649dbf36 3441 int sc, len;
cd591dbc
HE
3442 SELECT_TYPE fdset;
3443 retry_select:
3444 FD_ZERO (&fdset);
3445 FD_SET (s, &fdset);
3446 QUIT;
3447 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3448 (EMACS_TIME *)0);
3449 if (sc == -1)
3450 {
649dbf36 3451 if (errno == EINTR)
cd591dbc 3452 goto retry_select;
649dbf36 3453 else
cd591dbc
HE
3454 report_file_error ("select failed", Qnil);
3455 }
3456 eassert (sc > 0);
649dbf36
CY
3457
3458 len = sizeof xerrno;
3459 eassert (FD_ISSET (s, &fdset));
3460 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3461 report_file_error ("getsockopt failed", Qnil);
3462 if (xerrno)
3463 errno = xerrno, report_file_error ("error during connect", Qnil);
3464 else
3465 break;
cd591dbc 3466 }
649dbf36 3467#endif /* !WINDOWSNT */
e333e864 3468
0f2ee0c1
RS
3469 immediate_quit = 0;
3470
dd2a17ab 3471 /* Discard the unwind protect closing S. */
5684cd6e 3472 specpdl_ptr = specpdl + count1;
68c45bf0 3473 emacs_close (s);
dd2a17ab 3474 s = -1;
649dbf36
CY
3475
3476#ifdef WINDOWSNT
3477 if (xerrno == EINTR)
3478 goto retry_connect;
3479#endif
dd2a17ab 3480 }
457a9bee 3481
e690ca94
KS
3482 if (s >= 0)
3483 {
3484#ifdef DATAGRAM_SOCKETS
3485 if (socktype == SOCK_DGRAM)
3486 {
3487 if (datagram_address[s].sa)
3488 abort ();
3489 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3490 datagram_address[s].len = lres->ai_addrlen;
3491 if (is_server)
3492 {
3493 Lisp_Object remote;
72af86bd 3494 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
e690ca94
KS
3495 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3496 {
3497 int rfamily, rlen;
3498 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3499 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3500 conv_lisp_to_sockaddr (rfamily, remote,
3501 datagram_address[s].sa, rlen);
3502 }
3503 }
3504 else
72af86bd 3505 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
e690ca94
KS
3506 }
3507#endif
177c0ea7 3508 contact = Fplist_put (contact, QCaddress,
e690ca94 3509 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
2185db04
KS
3510#ifdef HAVE_GETSOCKNAME
3511 if (!is_server)
3512 {
3513 struct sockaddr_in sa1;
3514 int len1 = sizeof (sa1);
3515 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3516 contact = Fplist_put (contact, QClocal,
d3da34e0 3517 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
2185db04
KS
3518 }
3519#endif
e690ca94
KS
3520 }
3521
54b3b62f
YM
3522 immediate_quit = 0;
3523
dd2a17ab 3524#ifdef HAVE_GETADDRINFO
e690ca94 3525 if (res != &ai)
54b3b62f
YM
3526 {
3527 BLOCK_INPUT;
3528 freeaddrinfo (res);
3529 UNBLOCK_INPUT;
3530 }
dd2a17ab
KS
3531#endif
3532
e690ca94
KS
3533 /* Discard the unwind protect for closing S, if any. */
3534 specpdl_ptr = specpdl + count1;
3535
3536 /* Unwind bind_polling_period and request_sigio. */
3537 unbind_to (count, Qnil);
3538
dd2a17ab
KS
3539 if (s < 0)
3540 {
dd2a17ab
KS
3541 /* If non-blocking got this far - and failed - assume non-blocking is
3542 not supported after all. This is probably a wrong assumption, but
e690ca94
KS
3543 the normal blocking calls to open-network-stream handles this error
3544 better. */
3545 if (is_non_blocking_client)
dd2a17ab 3546 return Qnil;
dd2a17ab 3547
d0d6b7c5 3548 errno = xerrno;
e690ca94
KS
3549 if (is_server)
3550 report_file_error ("make server process failed", contact);
3551 else
3552 report_file_error ("make client process failed", contact);
d0d6b7c5 3553 }
44ade2e9 3554
d0d6b7c5 3555 inch = s;
59f23005 3556 outch = s;
d0d6b7c5
JB
3557
3558 if (!NILP (buffer))
3559 buffer = Fget_buffer_create (buffer);
3560 proc = make_process (name);
3561
3562 chan_process[inch] = proc;
3563
3564#ifdef O_NONBLOCK
3565 fcntl (inch, F_SETFL, O_NONBLOCK);
3566#else
3567#ifdef O_NDELAY
3568 fcntl (inch, F_SETFL, O_NDELAY);
3569#endif
3570#endif
3571
e690ca94
KS
3572 p = XPROCESS (proc);
3573
3574 p->childp = contact;
faa7db08 3575 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
d888760c 3576 p->type = Qnetwork;
177c0ea7 3577
e690ca94
KS
3578 p->buffer = buffer;
3579 p->sentinel = sentinel;
3580 p->filter = filter;
3581 p->log = Fplist_get (contact, QClog);
3582 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
60f0fb11 3583 p->kill_without_query = 1;
e690ca94
KS
3584 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3585 p->command = Qt;
6bfd98e7 3586 p->pid = 0;
60f0fb11
SM
3587 p->infd = inch;
3588 p->outfd = outch;
84b31826 3589 if (is_server && socktype != SOCK_DGRAM)
e690ca94 3590 p->status = Qlisten;
dd2a17ab 3591
f523e0c3
SM
3592 /* Make the process marker point into the process buffer (if any). */
3593 if (BUFFERP (buffer))
3594 set_marker_both (p->mark, buffer,
3595 BUF_ZV (XBUFFER (buffer)),
3596 BUF_ZV_BYTE (XBUFFER (buffer)));
3597
dd2a17ab 3598#ifdef NON_BLOCKING_CONNECT
e690ca94 3599 if (is_non_blocking_client)
dd2a17ab
KS
3600 {
3601 /* We may get here if connect did succeed immediately. However,
3602 in that case, we still need to signal this like a non-blocking
3603 connection. */
e690ca94 3604 p->status = Qconnect;
dd2a17ab
KS
3605 if (!FD_ISSET (inch, &connect_wait_mask))
3606 {
3607 FD_SET (inch, &connect_wait_mask);
3608 num_pending_connects++;
3609 }
3610 }
3611 else
3612#endif
e690ca94
KS
3613 /* A server may have a client filter setting of Qt, but it must
3614 still listen for incoming connects unless it is stopped. */
3615 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3616 || (EQ (p->status, Qlisten) && NILP (p->command)))
dd2a17ab
KS
3617 {
3618 FD_SET (inch, &input_wait_mask);
3619 FD_SET (inch, &non_keyboard_wait_mask);
3620 }
3621
7d0e672e
RS
3622 if (inch > max_process_desc)
3623 max_process_desc = inch;
d0d6b7c5 3624
e690ca94
KS
3625 tem = Fplist_member (contact, QCcoding);
3626 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3627 tem = Qnil; /* No error message (too late!). */
3628
67918941
RS
3629 {
3630 /* Setup coding systems for communicating with the network stream. */
3631 struct gcpro gcpro1;
3632 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3633 Lisp_Object coding_systems = Qt;
3634 Lisp_Object args[5], val;
3635
e690ca94 3636 if (!NILP (tem))
6b61353c
KH
3637 {
3638 val = XCAR (XCDR (tem));
3639 if (CONSP (val))
3640 val = XCAR (val);
3641 }
e690ca94 3642 else if (!NILP (Vcoding_system_for_read))
67918941 3643 val = Vcoding_system_for_read;
41d03b9a
GM
3644 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3645 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
67918941
RS
3646 /* We dare not decode end-of-line format by setting VAL to
3647 Qraw_text, because the existing Emacs Lisp libraries
3648 assume that they receive bare code including a sequene of
3649 CR LF. */
3650 val = Qnil;
3651 else
3652 {
991234f0
KS
3653 if (NILP (host) || NILP (service))
3654 coding_systems = Qnil;
3655 else
3656 {
3657 args[0] = Qopen_network_stream, args[1] = name,
3658 args[2] = buffer, args[3] = host, args[4] = service;
3659 GCPRO1 (proc);
3660 coding_systems = Ffind_operation_coding_system (5, args);
3661 UNGCPRO;
3662 }
67918941 3663 if (CONSP (coding_systems))
70949dac 3664 val = XCAR (coding_systems);
67918941 3665 else if (CONSP (Vdefault_process_coding_system))
70949dac 3666 val = XCAR (Vdefault_process_coding_system);
67918941
RS
3667 else
3668 val = Qnil;
3669 }
e690ca94 3670 p->decode_coding_system = val;
0fa1789e 3671
e690ca94 3672 if (!NILP (tem))
6b61353c
KH
3673 {
3674 val = XCAR (XCDR (tem));
3675 if (CONSP (val))
3676 val = XCDR (val);
3677 }
e690ca94 3678 else if (!NILP (Vcoding_system_for_write))
67918941
RS
3679 val = Vcoding_system_for_write;
3680 else if (NILP (current_buffer->enable_multibyte_characters))
3681 val = Qnil;
3682 else
3683 {
3684 if (EQ (coding_systems, Qt))
3685 {
991234f0
KS
3686 if (NILP (host) || NILP (service))
3687 coding_systems = Qnil;
3688 else
3689 {
3690 args[0] = Qopen_network_stream, args[1] = name,
3691 args[2] = buffer, args[3] = host, args[4] = service;
3692 GCPRO1 (proc);
3693 coding_systems = Ffind_operation_coding_system (5, args);
3694 UNGCPRO;
3695 }
67918941
RS
3696 }
3697 if (CONSP (coding_systems))
70949dac 3698 val = XCDR (coding_systems);
67918941 3699 else if (CONSP (Vdefault_process_coding_system))
70949dac 3700 val = XCDR (Vdefault_process_coding_system);
67918941
RS
3701 else
3702 val = Qnil;
3703 }
e690ca94 3704 p->encode_coding_system = val;
67918941 3705 }
03f04413 3706 setup_process_coding_systems (proc);
0fa1789e 3707
e690ca94 3708 p->decoding_buf = make_uninit_string (0);
60f0fb11 3709 p->decoding_carryover = 0;
e690ca94 3710 p->encoding_buf = make_uninit_string (0);
0fa1789e 3711
e690ca94 3712 p->inherit_coding_system_flag
e6fca843 3713 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
52a1b894 3714
d0d6b7c5
JB
3715 UNGCPRO;
3716 return proc;
3717}
d0d6b7c5 3718
6b61353c 3719\f
fce70521 3720#if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
6b61353c
KH
3721
3722#ifdef SIOCGIFCONF
3723DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3724 doc: /* Return an alist of all network interfaces and their network address.
3725Each element is a cons, the car of which is a string containing the
3726interface name, and the cdr is the network address in internal
3727format; see the description of ADDRESS in `make-network-process'. */)
5842a27b 3728 (void)
6b61353c
KH
3729{
3730 struct ifconf ifconf;
3731 struct ifreq *ifreqs = NULL;
3732 int ifaces = 0;
3733 int buf_size, s;
3734 Lisp_Object res;
3735
3736 s = socket (AF_INET, SOCK_STREAM, 0);
3737 if (s < 0)
3738 return Qnil;
3739
3740 again:
3741 ifaces += 25;
ed3751c8 3742 buf_size = ifaces * sizeof (ifreqs[0]);
6b61353c
KH
3743 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3744 if (!ifreqs)
3745 {
3746 close (s);
3747 return Qnil;
3748 }
3749
3750 ifconf.ifc_len = buf_size;
3751 ifconf.ifc_req = ifreqs;
3752 if (ioctl (s, SIOCGIFCONF, &ifconf))
3753 {
3754 close (s);
3755 return Qnil;
3756 }
3757
3758 if (ifconf.ifc_len == buf_size)
3759 goto again;
3760
3761 close (s);
3762 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3763
3764 res = Qnil;
3765 while (--ifaces >= 0)
3766 {
3767 struct ifreq *ifq = &ifreqs[ifaces];
3768 char namebuf[sizeof (ifq->ifr_name) + 1];
3769 if (ifq->ifr_addr.sa_family != AF_INET)
3770 continue;
72af86bd 3771 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
6b61353c
KH
3772 namebuf[sizeof (ifq->ifr_name)] = 0;
3773 res = Fcons (Fcons (build_string (namebuf),
3774 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3775 sizeof (struct sockaddr))),
3776 res);
3777 }
3778
3779 return res;
3780}
3781#endif /* SIOCGIFCONF */
3782
3783#if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3784
3785struct ifflag_def {
3786 int flag_bit;
91433552 3787 const char *flag_sym;
6b61353c
KH
3788};
3789
91433552 3790static const struct ifflag_def ifflag_table[] = {
6b61353c
KH
3791#ifdef IFF_UP
3792 { IFF_UP, "up" },
3793#endif
3794#ifdef IFF_BROADCAST
3795 { IFF_BROADCAST, "broadcast" },
3796#endif
3797#ifdef IFF_DEBUG
3798 { IFF_DEBUG, "debug" },
3799#endif
3800#ifdef IFF_LOOPBACK
3801 { IFF_LOOPBACK, "loopback" },
3802#endif
3803#ifdef IFF_POINTOPOINT
3804 { IFF_POINTOPOINT, "pointopoint" },
3805#endif
3806#ifdef IFF_RUNNING
3807 { IFF_RUNNING, "running" },
3808#endif
3809#ifdef IFF_NOARP
3810 { IFF_NOARP, "noarp" },
3811#endif
3812#ifdef IFF_PROMISC
3813 { IFF_PROMISC, "promisc" },
3814#endif
3815#ifdef IFF_NOTRAILERS
3816 { IFF_NOTRAILERS, "notrailers" },
3817#endif
3818#ifdef IFF_ALLMULTI
3819 { IFF_ALLMULTI, "allmulti" },
3820#endif
3821#ifdef IFF_MASTER
3822 { IFF_MASTER, "master" },
3823#endif
3824#ifdef IFF_SLAVE
3825 { IFF_SLAVE, "slave" },
3826#endif
3827#ifdef IFF_MULTICAST
3828 { IFF_MULTICAST, "multicast" },
3829#endif
3830#ifdef IFF_PORTSEL
3831 { IFF_PORTSEL, "portsel" },
3832#endif
3833#ifdef IFF_AUTOMEDIA
3834 { IFF_AUTOMEDIA, "automedia" },
3835#endif
3836#ifdef IFF_DYNAMIC
3837 { IFF_DYNAMIC, "dynamic" },
e1652a86 3838#endif
2026418c
YM
3839#ifdef IFF_OACTIVE
3840 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
e1652a86
KS
3841#endif
3842#ifdef IFF_SIMPLEX
3843 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3844#endif
3845#ifdef IFF_LINK0
3846 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3847#endif
3848#ifdef IFF_LINK1
3849 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3850#endif
3851#ifdef IFF_LINK2
3852 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
6b61353c
KH
3853#endif
3854 { 0, 0 }
3855};
3856
3857DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3858 doc: /* Return information about network interface named IFNAME.
3859The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3860where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3861NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3862FLAGS is the current flags of the interface. */)
5842a27b 3863 (Lisp_Object ifname)
6b61353c
KH
3864{
3865 struct ifreq rq;
3866 Lisp_Object res = Qnil;
3867 Lisp_Object elt;
3868 int s;
3869 int any = 0;
3870
3871 CHECK_STRING (ifname);
3872
72af86bd 3873 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
6b61353c
KH
3874 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3875
3876 s = socket (AF_INET, SOCK_STREAM, 0);
3877 if (s < 0)
3878 return Qnil;
3879
3880 elt = Qnil;
3881#if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3882 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3883 {
3884 int flags = rq.ifr_flags;
91433552 3885 const struct ifflag_def *fp;
6b61353c
KH
3886 int fnum;
3887
3888 any++;
82a80058 3889 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
6b61353c
KH
3890 {
3891 if (flags & fp->flag_bit)
3892 {
3893 elt = Fcons (intern (fp->flag_sym), elt);
3894 flags -= fp->flag_bit;
3895 }
3896 }
3897 for (fnum = 0; flags && fnum < 32; fnum++)
3898 {
3899 if (flags & (1 << fnum))
3900 {
3901 elt = Fcons (make_number (fnum), elt);
3902 }
3903 }
3904 }
3905#endif
3906 res = Fcons (elt, res);
3907
3908 elt = Qnil;
3909#if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3910 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3911 {
3912 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3913 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3914 int n;
3915
3916 any++;
3917 for (n = 0; n < 6; n++)
3918 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3919 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3920 }
3921#endif
3922 res = Fcons (elt, res);
3923
3924 elt = Qnil;
2026418c 3925#if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
6b61353c
KH
3926 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3927 {
3928 any++;
2026418c 3929#ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
6b61353c 3930 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
2026418c
YM
3931#else
3932 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3933#endif
6b61353c
KH
3934 }
3935#endif
3936 res = Fcons (elt, res);
3937
3938 elt = Qnil;
3939#if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3940 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3941 {
3942 any++;
3943 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3944 }
3945#endif
3946 res = Fcons (elt, res);
3947
3948 elt = Qnil;
3949#if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
3950 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3951 {
3952 any++;
3953 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3954 }
3955#endif
3956 res = Fcons (elt, res);
3957
3958 close (s);
3959
3960 return any ? res : Qnil;
3961}
3962#endif
fce70521 3963#endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
6b61353c 3964
04391069
RS
3965/* Turn off input and output for process PROC. */
3966
6b53bb85 3967void
d3da34e0 3968deactivate_process (Lisp_Object proc)
d0d6b7c5
JB
3969{
3970 register int inchannel, outchannel;
3971 register struct Lisp_Process *p = XPROCESS (proc);
3972
60f0fb11
SM
3973 inchannel = p->infd;
3974 outchannel = p->outfd;
d0d6b7c5 3975
6b61353c 3976#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11 3977 if (p->read_output_delay > 0)
6b61353c
KH
3978 {
3979 if (--process_output_delay_count < 0)
3980 process_output_delay_count = 0;
60f0fb11
SM
3981 p->read_output_delay = 0;
3982 p->read_output_skip = 0;
6b61353c
KH
3983 }
3984#endif
f3d9532b 3985
a9f2c884 3986 if (inchannel >= 0)
d0d6b7c5
JB
3987 {
3988 /* Beware SIGCHLD hereabouts. */
3989 flush_pending_output (inchannel);
68c45bf0 3990 emacs_close (inchannel);
a9f2c884 3991 if (outchannel >= 0 && outchannel != inchannel)
68c45bf0 3992 emacs_close (outchannel);
d0d6b7c5 3993
60f0fb11
SM
3994 p->infd = -1;
3995 p->outfd = -1;
e690ca94
KS
3996#ifdef DATAGRAM_SOCKETS
3997 if (DATAGRAM_CHAN_P (inchannel))
3998 {
3999 xfree (datagram_address[inchannel].sa);
4000 datagram_address[inchannel].sa = 0;
4001 datagram_address[inchannel].len = 0;
4002 }
4003#endif
d0d6b7c5
JB
4004 chan_process[inchannel] = Qnil;
4005 FD_CLR (inchannel, &input_wait_mask);
a69281ff 4006 FD_CLR (inchannel, &non_keyboard_wait_mask);
bad49fc7 4007#ifdef NON_BLOCKING_CONNECT
dd2a17ab
KS
4008 if (FD_ISSET (inchannel, &connect_wait_mask))
4009 {
4010 FD_CLR (inchannel, &connect_wait_mask);
4011 if (--num_pending_connects < 0)
4012 abort ();
4013 }
bad49fc7 4014#endif
7d0e672e
RS
4015 if (inchannel == max_process_desc)
4016 {
4017 int i;
4018 /* We just closed the highest-numbered process input descriptor,
4019 so recompute the highest-numbered one now. */
4020 max_process_desc = 0;
4021 for (i = 0; i < MAXDESC; i++)
4022 if (!NILP (chan_process[i]))
4023 max_process_desc = i;
4024 }
d0d6b7c5
JB
4025 }
4026}
4027
d0d6b7c5
JB
4028\f
4029DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
107ed38d 4030 0, 4, 0,
fdb82f93
PJ
4031 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4032It is read into the process' buffers or given to their filter functions.
4033Non-nil arg PROCESS means do not return until some output has been received
4034from PROCESS.
5088da42 4035
2a7bb882
MR
4036Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4037and milliseconds to wait; return after that much time whether or not
4038there is any subprocess output. If SECONDS is a floating point number,
5088da42 4039it specifies a fractional number of seconds to wait.
891bd142 4040The MILLISEC argument is obsolete and should be avoided.
5088da42 4041
107ed38d
KS
4042If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4043from PROCESS, suspending reading output from other processes.
4044If JUST-THIS-ONE is an integer, don't run any timers either.
e0f24100 4045Return non-nil if we received any output before the timeout expired. */)
5842a27b 4046 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
d0d6b7c5 4047{
5088da42 4048 int secs, usecs = 0;
d0d6b7c5 4049
0748d150 4050 if (! NILP (process))
b7826503 4051 CHECK_PROCESS (process);
107ed38d
KS
4052 else
4053 just_this_one = Qnil;
0748d150 4054
891bd142
SM
4055 if (!NILP (millisec))
4056 { /* Obsolete calling convention using integers rather than floats. */
4057 CHECK_NUMBER (millisec);
4058 if (NILP (seconds))
4059 seconds = make_float (XINT (millisec) / 1000.0);
4060 else
4061 {
4062 CHECK_NUMBER (seconds);
4063 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4064 }
4065 }
4066
5088da42 4067 if (!NILP (seconds))
d0d6b7c5 4068 {
5088da42
KS
4069 if (INTEGERP (seconds))
4070 secs = XINT (seconds);
4071 else if (FLOATP (seconds))
4072 {
4073 double timeout = XFLOAT_DATA (seconds);
4074 secs = (int) timeout;
4075 usecs = (int) ((timeout - (double) secs) * 1000000);
4076 }
4077 else
4078 wrong_type_argument (Qnumberp, seconds);
d0d6b7c5 4079
5088da42
KS
4080 if (secs < 0 || (secs == 0 && usecs == 0))
4081 secs = -1, usecs = 0;
d0d6b7c5
JB
4082 }
4083 else
5088da42 4084 secs = NILP (process) ? -1 : 0;
d0d6b7c5
JB
4085
4086 return
5088da42 4087 (wait_reading_process_output (secs, usecs, 0, 0,
214d6069
KS
4088 Qnil,
4089 !NILP (process) ? XPROCESS (process) : NULL,
4090 NILP (just_this_one) ? 0 :
4091 !INTEGERP (just_this_one) ? 1 : -1)
d0d6b7c5
JB
4092 ? Qt : Qnil);
4093}
4094
e690ca94
KS
4095/* Accept a connection for server process SERVER on CHANNEL. */
4096
4097static int connect_counter = 0;
4098
4099static void
d3da34e0 4100server_accept_connection (Lisp_Object server, int channel)
e690ca94
KS
4101{
4102 Lisp_Object proc, caller, name, buffer;
4103 Lisp_Object contact, host, service;
4104 struct Lisp_Process *ps= XPROCESS (server);
4105 struct Lisp_Process *p;
4106 int s;
4107 union u_sockaddr {
4108 struct sockaddr sa;
4109 struct sockaddr_in in;
e1652a86
KS
4110#ifdef AF_INET6
4111 struct sockaddr_in6 in6;
4112#endif
e690ca94
KS
4113#ifdef HAVE_LOCAL_SOCKETS
4114 struct sockaddr_un un;
4115#endif
4116 } saddr;
4117 int len = sizeof saddr;
4118
4119 s = accept (channel, &saddr.sa, &len);
4120
4121 if (s < 0)
4122 {
4123 int code = errno;
4124
4125 if (code == EAGAIN)
4126 return;
4127#ifdef EWOULDBLOCK
4128 if (code == EWOULDBLOCK)
4129 return;
4130#endif
4131
4132 if (!NILP (ps->log))
4133 call3 (ps->log, server, Qnil,
4134 concat3 (build_string ("accept failed with code"),
4135 Fnumber_to_string (make_number (code)),
4136 build_string ("\n")));
4137 return;
4138 }
4139
4140 connect_counter++;
4141
4142 /* Setup a new process to handle the connection. */
4143
4144 /* Generate a unique identification of the caller, and build contact
4145 information for this process. */
4146 host = Qt;
4147 service = Qnil;
4148 switch (saddr.sa.sa_family)
4149 {
4150 case AF_INET:
4151 {
4152 Lisp_Object args[5];
4153 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4154 args[0] = build_string ("%d.%d.%d.%d");
4155 args[1] = make_number (*ip++);
4156 args[2] = make_number (*ip++);
4157 args[3] = make_number (*ip++);
4158 args[4] = make_number (*ip++);
4159 host = Fformat (5, args);
4160 service = make_number (ntohs (saddr.in.sin_port));
4161
4162 args[0] = build_string (" <%s:%d>");
4163 args[1] = host;
4164 args[2] = service;
4165 caller = Fformat (3, args);
4166 }
4167 break;
4168
e1652a86
KS
4169#ifdef AF_INET6
4170 case AF_INET6:
4171 {
4172 Lisp_Object args[9];
4173 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4174 int i;
4175 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4176 for (i = 0; i < 8; i++)
ed3751c8 4177 args[i+1] = make_number (ntohs (ip6[i]));
e1652a86
KS
4178 host = Fformat (9, args);
4179 service = make_number (ntohs (saddr.in.sin_port));
4180
4181 args[0] = build_string (" <[%s]:%d>");
4182 args[1] = host;
4183 args[2] = service;
4184 caller = Fformat (3, args);
4185 }
4186 break;
4187#endif
4188
e690ca94
KS
4189#ifdef HAVE_LOCAL_SOCKETS
4190 case AF_LOCAL:
4191#endif
4192 default:
4193 caller = Fnumber_to_string (make_number (connect_counter));
eef60308 4194 caller = concat3 (build_string (" <"), caller, build_string (">"));
e690ca94
KS
4195 break;
4196 }
4197
4198 /* Create a new buffer name for this process if it doesn't have a
4199 filter. The new buffer name is based on the buffer name or
4200 process name of the server process concatenated with the caller
4201 identification. */
4202
4203 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4204 buffer = Qnil;
4205 else
4206 {
4207 buffer = ps->buffer;
4208 if (!NILP (buffer))
4209 buffer = Fbuffer_name (buffer);
4210 else
4211 buffer = ps->name;
4212 if (!NILP (buffer))
4213 {
4214 buffer = concat2 (buffer, caller);
4215 buffer = Fget_buffer_create (buffer);
4216 }
4217 }
4218
4219 /* Generate a unique name for the new server process. Combine the
4220 server process name with the caller identification. */
4221
4222 name = concat2 (ps->name, caller);
4223 proc = make_process (name);
4224
4225 chan_process[s] = proc;
4226
4227#ifdef O_NONBLOCK
4228 fcntl (s, F_SETFL, O_NONBLOCK);
4229#else
4230#ifdef O_NDELAY
4231 fcntl (s, F_SETFL, O_NDELAY);
4232#endif
4233#endif
4234
4235 p = XPROCESS (proc);
4236
4237 /* Build new contact information for this setup. */
4238 contact = Fcopy_sequence (ps->childp);
4239 contact = Fplist_put (contact, QCserver, Qnil);
4240 contact = Fplist_put (contact, QChost, host);
4241 if (!NILP (service))
4242 contact = Fplist_put (contact, QCservice, service);
177c0ea7 4243 contact = Fplist_put (contact, QCremote,
e690ca94
KS
4244 conv_sockaddr_to_lisp (&saddr.sa, len));
4245#ifdef HAVE_GETSOCKNAME
4246 len = sizeof saddr;
2185db04 4247 if (getsockname (s, &saddr.sa, &len) == 0)
177c0ea7 4248 contact = Fplist_put (contact, QClocal,
e690ca94
KS
4249 conv_sockaddr_to_lisp (&saddr.sa, len));
4250#endif
4251
4252 p->childp = contact;
faa7db08 4253 p->plist = Fcopy_sequence (ps->plist);
d888760c 4254 p->type = Qnetwork;
ac4a7584 4255
e690ca94
KS
4256 p->buffer = buffer;
4257 p->sentinel = ps->sentinel;
4258 p->filter = ps->filter;
4259 p->command = Qnil;
6bfd98e7 4260 p->pid = 0;
60f0fb11
SM
4261 p->infd = s;
4262 p->outfd = s;
e690ca94
KS
4263 p->status = Qrun;
4264
4265 /* Client processes for accepted connections are not stopped initially. */
4266 if (!EQ (p->filter, Qt))
4267 {
4268 FD_SET (s, &input_wait_mask);
4269 FD_SET (s, &non_keyboard_wait_mask);
4270 }
4271
4272 if (s > max_process_desc)
4273 max_process_desc = s;
4274
177c0ea7 4275 /* Setup coding system for new process based on server process.
e690ca94
KS
4276 This seems to be the proper thing to do, as the coding system
4277 of the new process should reflect the settings at the time the
4278 server socket was opened; not the current settings. */
4279
4280 p->decode_coding_system = ps->decode_coding_system;
4281 p->encode_coding_system = ps->encode_coding_system;
03f04413 4282 setup_process_coding_systems (proc);
e690ca94
KS
4283
4284 p->decoding_buf = make_uninit_string (0);
60f0fb11 4285 p->decoding_carryover = 0;
e690ca94 4286 p->encoding_buf = make_uninit_string (0);
e690ca94
KS
4287
4288 p->inherit_coding_system_flag
60f0fb11 4289 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
e690ca94
KS
4290
4291 if (!NILP (ps->log))
4292 call3 (ps->log, server, proc,
4293 concat3 (build_string ("accept from "),
4294 (STRINGP (host) ? host : build_string ("-")),
4295 build_string ("\n")));
4296
bed9664a 4297 if (!NILP (p->sentinel))
177c0ea7 4298 exec_sentinel (proc,
e690ca94
KS
4299 concat3 (build_string ("open from "),
4300 (STRINGP (host) ? host : build_string ("-")),
4301 build_string ("\n")));
4302}
4303
d0d6b7c5
JB
4304/* This variable is different from waiting_for_input in keyboard.c.
4305 It is used to communicate to a lisp process-filter/sentinel (via the
f3d9532b 4306 function Fwaiting_for_user_input_p below) whether Emacs was waiting
d0d6b7c5
JB
4307 for user-input when that process-filter was called.
4308 waiting_for_input cannot be used as that is by definition 0 when
d430ee71
RS
4309 lisp code is being evalled.
4310 This is also used in record_asynch_buffer_change.
4311 For that purpose, this must be 0
214d6069 4312 when not inside wait_reading_process_output. */
d0d6b7c5
JB
4313static int waiting_for_user_input_p;
4314
2beb96f9 4315static Lisp_Object
d3da34e0 4316wait_reading_process_output_unwind (Lisp_Object data)
2beb96f9
KS
4317{
4318 waiting_for_user_input_p = XINT (data);
4319 return Qnil;
4320}
4321
c573ae8e 4322/* This is here so breakpoints can be put on it. */
dfcf069d 4323static void
d3da34e0 4324wait_reading_process_output_1 (void)
c573ae8e
RS
4325{
4326}
4327
e1e541bd 4328/* Use a wrapper around select to work around a bug in gdb 5.3.
96c834b6 4329 Normally, the wrapper is optimized away by inlining.
e1e541bd
KS
4330
4331 If emacs is stopped inside select, the gdb backtrace doesn't
4332 show the function which called select, so it is practically
4333 impossible to step through wait_reading_process_output. */
4334
4335#ifndef select
4336static INLINE int
d3da34e0 4337select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
e1e541bd
KS
4338{
4339 return select (n, rfd, wfd, xfd, tmo);
4340}
4341#define select select_wrapper
4342#endif
4343
d0d6b7c5
JB
4344/* Read and dispose of subprocess output while waiting for timeout to
4345 elapse and/or keyboard input to be available.
4346
de6fd4b9 4347 TIME_LIMIT is:
d0d6b7c5
JB
4348 timeout in seconds, or
4349 zero for no limit, or
4350 -1 means gobble data immediately available but don't wait for any.
4351
de6fd4b9
RS
4352 MICROSECS is:
4353 an additional duration to wait, measured in microseconds.
4354 If this is nonzero and time_limit is 0, then the timeout
4355 consists of MICROSECS only.
6e4f3667 4356
de6fd4b9 4357 READ_KBD is a lisp value:
d0d6b7c5
JB
4358 0 to ignore keyboard input, or
4359 1 to return when input is available, or
84aa3ace 4360 -1 meaning caller will actually read the input, so don't throw to
d0d6b7c5 4361 the quit handler, or
d0d6b7c5 4362
de6fd4b9 4363 DO_DISPLAY != 0 means redisplay should be done to show subprocess
107ed38d 4364 output that arrives.
d0d6b7c5 4365
b89a415a
KS
4366 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4367 (and gobble terminal input into the buffer if any arrives).
d0d6b7c5 4368
b89a415a 4369 If WAIT_PROC is specified, wait until something arrives from that
e0f24100 4370 process. The return value is true if we read some input from
b89a415a
KS
4371 that process.
4372
4373 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4374 (suspending output from other processes). A negative value
4375 means don't run any timers either.
4376
e0f24100 4377 If WAIT_PROC is specified, then the function returns true if we
b89a415a 4378 received input from that process before the timeout elapsed.
e0f24100 4379 Otherwise, return true if we received input from any process. */
d0d6b7c5 4380
dfcf069d 4381int
d5a3eaaf
AS
4382wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4383 int do_display,
4384 Lisp_Object wait_for_cell,
4385 struct Lisp_Process *wait_proc, int just_wait_proc)
d0d6b7c5 4386{
41d03b9a 4387 register int channel, nfds;
855448dc 4388 SELECT_TYPE Available;
bad49fc7 4389#ifdef NON_BLOCKING_CONNECT
855448dc 4390 SELECT_TYPE Connecting;
bad49fc7
KS
4391 int check_connect;
4392#endif
4393 int check_delay, no_avail;
d0d6b7c5
JB
4394 int xerrno;
4395 Lisp_Object proc;
41d03b9a 4396 EMACS_TIME timeout, end_time;
a9f2c884 4397 int wait_channel = -1;
d0d6b7c5 4398 int got_some_input = 0;
2beb96f9 4399 int count = SPECPDL_INDEX ();
d0d6b7c5
JB
4400
4401 FD_ZERO (&Available);
bad49fc7 4402#ifdef NON_BLOCKING_CONNECT
dd2a17ab 4403 FD_ZERO (&Connecting);
bad49fc7 4404#endif
d0d6b7c5 4405
283357a7 4406 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
2b0a91e7
SM
4407 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4408 message ("Blocking call to accept-process-output with quit inhibited!!");
4409
b89a415a
KS
4410 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4411 if (wait_proc != NULL)
60f0fb11 4412 wait_channel = wait_proc->infd;
84aa3ace 4413
2beb96f9
KS
4414 record_unwind_protect (wait_reading_process_output_unwind,
4415 make_number (waiting_for_user_input_p));
b89a415a 4416 waiting_for_user_input_p = read_kbd;
d0d6b7c5
JB
4417
4418 /* Since we may need to wait several times,
4419 compute the absolute time to return at. */
4420 if (time_limit || microsecs)
4421 {
4422 EMACS_GET_TIME (end_time);
4423 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4424 EMACS_ADD_TIME (end_time, end_time, timeout);
4425 }
4426
d0d6b7c5
JB
4427 while (1)
4428 {
c0239a0b
RS
4429 int timeout_reduced_for_timers = 0;
4430
d0d6b7c5
JB
4431 /* If calling from keyboard input, do not quit
4432 since we want to return C-g as an input character.
4433 Otherwise, do pending quit if requested. */
b89a415a 4434 if (read_kbd >= 0)
d0d6b7c5 4435 QUIT;
6b61353c 4436#ifdef SYNC_INPUT
ef5eb925 4437 else
c3eff1b0 4438 process_pending_signals ();
6b61353c 4439#endif
d0d6b7c5 4440
889255b4 4441 /* Exit now if the cell we're waiting for became non-nil. */
f3fbd155 4442 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
889255b4
RS
4443 break;
4444
d0d6b7c5
JB
4445 /* Compute time from now till when time limit is up */
4446 /* Exit if already run out */
4447 if (time_limit == -1)
4448 {
4449 /* -1 specified for timeout means
4450 gobble output available now
4451 but don't wait at all. */
4452
4453 EMACS_SET_SECS_USECS (timeout, 0, 0);
4454 }
4455 else if (time_limit || microsecs)
4456 {
4457 EMACS_GET_TIME (timeout);
4458 EMACS_SUB_TIME (timeout, end_time, timeout);
4459 if (EMACS_TIME_NEG_P (timeout))
4460 break;
4461 }
4462 else
4463 {
4464 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4465 }
4466
f854a00b
RS
4467 /* Normally we run timers here.
4468 But not if wait_for_cell; in those cases,
4469 the wait is supposed to be short,
4470 and those callers cannot handle running arbitrary Lisp code here. */
107ed38d 4471 if (NILP (wait_for_cell)
b89a415a 4472 && just_wait_proc >= 0)
fb4c3627 4473 {
c0239a0b 4474 EMACS_TIME timer_delay;
c573ae8e 4475
9baacf76 4476 do
c573ae8e 4477 {
9baacf76 4478 int old_timers_run = timers_run;
c88164fe 4479 struct buffer *old_buffer = current_buffer;
70bb1e5f 4480 Lisp_Object old_window = selected_window;
177c0ea7 4481
9baacf76 4482 timer_delay = timer_check (1);
a2fab450
GM
4483
4484 /* If a timer has run, this might have changed buffers
4485 an alike. Make read_key_sequence aware of that. */
4486 if (timers_run != old_timers_run
70bb1e5f
CY
4487 && (old_buffer != current_buffer
4488 || !EQ (old_window, selected_window))
a2fab450
GM
4489 && waiting_for_user_input_p == -1)
4490 record_asynch_buffer_change ();
177c0ea7 4491
9baacf76
GM
4492 if (timers_run != old_timers_run && do_display)
4493 /* We must retry, since a timer may have requeued itself
4494 and that could alter the time_delay. */
3007ebfb 4495 redisplay_preserve_echo_area (9);
9baacf76
GM
4496 else
4497 break;
c573ae8e 4498 }
9baacf76 4499 while (!detect_input_pending ());
c573ae8e 4500
69645afc 4501 /* If there is unread keyboard input, also return. */
b89a415a 4502 if (read_kbd != 0
69645afc
RS
4503 && requeued_events_pending_p ())
4504 break;
4505
c0239a0b 4506 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
fb4c3627
RS
4507 {
4508 EMACS_TIME difference;
4509 EMACS_SUB_TIME (difference, timer_delay, timeout);
4510 if (EMACS_TIME_NEG_P (difference))
c0239a0b
RS
4511 {
4512 timeout = timer_delay;
4513 timeout_reduced_for_timers = 1;
4514 }
fb4c3627 4515 }
4abca5e7
RS
4516 /* If time_limit is -1, we are not going to wait at all. */
4517 else if (time_limit != -1)
c573ae8e
RS
4518 {
4519 /* This is so a breakpoint can be put here. */
214d6069 4520 wait_reading_process_output_1 ();
c573ae8e 4521 }
fb4c3627
RS
4522 }
4523
90ab1a81
JB
4524 /* Cause C-g and alarm signals to take immediate action,
4525 and cause input available signals to zero out timeout.
4526
4527 It is important that we do this before checking for process
4528 activity. If we get a SIGCHLD after the explicit checks for
4529 process activity, timeout is the only way we will know. */
b89a415a 4530 if (read_kbd < 0)
90ab1a81
JB
4531 set_waiting_for_input (&timeout);
4532
6be429b1
JB
4533 /* If status of something has changed, and no input is
4534 available, notify the user of the change right away. After
4535 this explicit check, we'll let the SIGCHLD handler zap
e42bdf01
CY
4536 timeout to get our attention. */
4537 if (update_tick != process_tick)
6be429b1 4538 {
bad49fc7
KS
4539 SELECT_TYPE Atemp;
4540#ifdef NON_BLOCKING_CONNECT
4541 SELECT_TYPE Ctemp;
4542#endif
dd2a17ab 4543
cb768704
J
4544 if (kbd_on_hold_p ())
4545 FD_ZERO (&Atemp);
4546 else
4547 Atemp = input_wait_mask;
bad49fc7
KS
4548 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4549
6be429b1 4550 EMACS_SET_SECS_USECS (timeout, 0, 0);
994d9841
NR
4551 if ((select (max (max (max_process_desc, max_keyboard_desc),
4552 max_gpm_desc) + 1,
177c0ea7 4553 &Atemp,
bad49fc7 4554#ifdef NON_BLOCKING_CONNECT
dd2a17ab 4555 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
bad49fc7
KS
4556#else
4557 (SELECT_TYPE *)0,
4558#endif
dd2a17ab 4559 (SELECT_TYPE *)0, &timeout)
ecd1f654 4560 <= 0))
90ab1a81
JB
4561 {
4562 /* It's okay for us to do this and then continue with
a0e4d3f3 4563 the loop, since timeout has already been zeroed out. */
90ab1a81 4564 clear_waiting_for_input ();
ff6daed3 4565 status_notify (NULL);
e42bdf01 4566 if (do_display) redisplay_preserve_echo_area (13);
90ab1a81 4567 }
6be429b1
JB
4568 }
4569
dd2a17ab 4570 /* Don't wait for output from a non-running process. Just
63136da6 4571 read whatever data has already been received. */
6bfd98e7 4572 if (wait_proc && wait_proc->raw_status_new)
6be429b1 4573 update_status (wait_proc);
6bfd98e7 4574 if (wait_proc
dd2a17ab
KS
4575 && ! EQ (wait_proc->status, Qrun)
4576 && ! EQ (wait_proc->status, Qconnect))
9aa2a7f4 4577 {
215b45e9 4578 int nread, total_nread = 0;
7ce63188 4579
9aa2a7f4 4580 clear_waiting_for_input ();
7ce63188
RS
4581 XSETPROCESS (proc, wait_proc);
4582
4583 /* Read data from the process, until we exhaust it. */
60f0fb11 4584 while (wait_proc->infd >= 0)
215b45e9 4585 {
60f0fb11 4586 nread = read_process_output (proc, wait_proc->infd);
e1b37c34
GM
4587
4588 if (nread == 0)
4589 break;
4590
63136da6
AS
4591 if (0 < nread)
4592 {
891bd142
SM
4593 total_nread += nread;
4594 got_some_input = 1;
4595 }
215b45e9
RS
4596#ifdef EIO
4597 else if (nread == -1 && EIO == errno)
63136da6 4598 break;
e1b37c34
GM
4599#endif
4600#ifdef EAGAIN
4601 else if (nread == -1 && EAGAIN == errno)
63136da6 4602 break;
e1b37c34
GM
4603#endif
4604#ifdef EWOULDBLOCK
4605 else if (nread == -1 && EWOULDBLOCK == errno)
63136da6 4606 break;
215b45e9
RS
4607#endif
4608 }
7ce63188 4609 if (total_nread > 0 && do_display)
3007ebfb 4610 redisplay_preserve_echo_area (10);
7ce63188 4611
9aa2a7f4
JB
4612 break;
4613 }
6be429b1 4614
d0d6b7c5
JB
4615 /* Wait till there is something to do */
4616
b89a415a 4617 if (wait_proc && just_wait_proc)
107ed38d 4618 {
60f0fb11 4619 if (wait_proc->infd < 0) /* Terminated */
b89a415a 4620 break;
60f0fb11 4621 FD_SET (wait_proc->infd, &Available);
bad49fc7
KS
4622 check_delay = 0;
4623 IF_NON_BLOCKING_CONNECT (check_connect = 0);
107ed38d
KS
4624 }
4625 else if (!NILP (wait_for_cell))
dd2a17ab
KS
4626 {
4627 Available = non_process_wait_mask;
bad49fc7
KS
4628 check_delay = 0;
4629 IF_NON_BLOCKING_CONNECT (check_connect = 0);
dd2a17ab 4630 }
a69281ff 4631 else
dd2a17ab 4632 {
b89a415a 4633 if (! read_kbd)
dd2a17ab
KS
4634 Available = non_keyboard_wait_mask;
4635 else
4636 Available = input_wait_mask;
bad49fc7 4637 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
6b61353c 4638 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
dd2a17ab 4639 }
d0d6b7c5 4640
ff11dfa1 4641 /* If frame size has changed or the window is newly mapped,
ffd56f97
JB
4642 redisplay now, before we start to wait. There is a race
4643 condition here; if a SIGIO arrives between now and the select
016899c0
JB
4644 and indicates that a frame is trashed, the select may block
4645 displaying a trashed screen. */
5164ee8e 4646 if (frame_garbaged && do_display)
7286affd
RS
4647 {
4648 clear_waiting_for_input ();
3007ebfb 4649 redisplay_preserve_echo_area (11);
b89a415a 4650 if (read_kbd < 0)
7efe788e 4651 set_waiting_for_input (&timeout);
7286affd 4652 }
ffd56f97 4653
dd2a17ab 4654 no_avail = 0;
b89a415a 4655 if (read_kbd && detect_input_pending ())
0a65b032
RS
4656 {
4657 nfds = 0;
dd2a17ab 4658 no_avail = 1;
0a65b032
RS
4659 }
4660 else
dd2a17ab 4661 {
bad49fc7 4662#ifdef NON_BLOCKING_CONNECT
dd2a17ab
KS
4663 if (check_connect)
4664 Connecting = connect_wait_mask;
bad49fc7 4665#endif
6b61353c
KH
4666
4667#ifdef ADAPTIVE_READ_BUFFERING
db853b7a 4668 /* Set the timeout for adaptive read buffering if any
60f0fb11 4669 process has non-zero read_output_skip and non-zero
db853b7a
KS
4670 read_output_delay, and we are not reading output for a
4671 specific wait_channel. It is not executed if
4672 Vprocess_adaptive_read_buffering is nil. */
6b61353c
KH
4673 if (process_output_skip && check_delay > 0)
4674 {
4675 int usecs = EMACS_USECS (timeout);
4676 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4677 usecs = READ_OUTPUT_DELAY_MAX;
4678 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4679 {
4680 proc = chan_process[channel];
4681 if (NILP (proc))
4682 continue;
db853b7a 4683 /* Find minimum non-zero read_output_delay among the
60f0fb11
SM
4684 processes with non-zero read_output_skip. */
4685 if (XPROCESS (proc)->read_output_delay > 0)
6b61353c
KH
4686 {
4687 check_delay--;
60f0fb11 4688 if (!XPROCESS (proc)->read_output_skip)
6b61353c
KH
4689 continue;
4690 FD_CLR (channel, &Available);
60f0fb11
SM
4691 XPROCESS (proc)->read_output_skip = 0;
4692 if (XPROCESS (proc)->read_output_delay < usecs)
4693 usecs = XPROCESS (proc)->read_output_delay;
6b61353c
KH
4694 }
4695 }
4696 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4697 process_output_skip = 0;
4698 }
4699#endif
872870b2
JD
4700#if defined (USE_GTK) || defined (HAVE_GCONF)
4701 nfds = xg_select
4702#elif defined (HAVE_NS)
63136da6 4703 nfds = ns_select
edfda783 4704#else
63136da6 4705 nfds = select
edfda783 4706#endif
63136da6 4707 (max (max (max_process_desc, max_keyboard_desc),
994d9841 4708 max_gpm_desc) + 1,
177c0ea7 4709 &Available,
bad49fc7 4710#ifdef NON_BLOCKING_CONNECT
dd2a17ab 4711 (check_connect ? &Connecting : (SELECT_TYPE *)0),
bad49fc7
KS
4712#else
4713 (SELECT_TYPE *)0,
4714#endif
dd2a17ab
KS
4715 (SELECT_TYPE *)0, &timeout);
4716 }
6720a7fb 4717
d0d6b7c5
JB
4718 xerrno = errno;
4719
4720 /* Make C-g and alarm signals set flags again */
4721 clear_waiting_for_input ();
4722
4723 /* If we woke up due to SIGWINCH, actually change size now. */
2b653806 4724 do_pending_window_change (0);
d0d6b7c5 4725
c0239a0b
RS
4726 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4727 /* We wanted the full specified time, so return now. */
d0d6b7c5
JB
4728 break;
4729 if (nfds < 0)
4730 {
4731 if (xerrno == EINTR)
dd2a17ab 4732 no_avail = 1;
d0d6b7c5
JB
4733 else if (xerrno == EBADF)
4734 {
4735#ifdef AIX
4736 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4737 the child's closure of the pts gives the parent a SIGHUP, and
4738 the ptc file descriptor is automatically closed,
4739 yielding EBADF here or at select() call above.
4740 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
a0e4d3f3 4741 in m/ibmrt-aix.h), and here we just ignore the select error.
d0d6b7c5 4742 Cleanup occurs c/o status_notify after SIGCLD. */
dd2a17ab 4743 no_avail = 1; /* Cannot depend on values returned */
d0d6b7c5
JB
4744#else
4745 abort ();
4746#endif
4747 }
4748 else
68c45bf0 4749 error ("select error: %s", emacs_strerror (xerrno));
d0d6b7c5 4750 }
dd2a17ab
KS
4751
4752 if (no_avail)
4753 {
4754 FD_ZERO (&Available);
bad49fc7 4755 IF_NON_BLOCKING_CONNECT (check_connect = 0);
dd2a17ab
KS
4756 }
4757
5d5beb62
RS
4758#if 0 /* When polling is used, interrupt_input is 0,
4759 so get_input_pending should read the input.
4760 So this should not be needed. */
4761 /* If we are using polling for input,
4762 and we see input available, make it get read now.
4763 Otherwise it might not actually get read for a second.
214d6069 4764 And on hpux, since we turn off polling in wait_reading_process_output,
5d5beb62 4765 it might never get read at all if we don't spend much time
214d6069 4766 outside of wait_reading_process_output. */
b89a415a 4767 if (read_kbd && interrupt_input
5d5beb62
RS
4768 && keyboard_bit_set (&Available)
4769 && input_polling_used ())
4770 kill (getpid (), SIGALRM);
4771#endif
4772
d0d6b7c5
JB
4773 /* Check for keyboard input */
4774 /* If there is any, return immediately
4775 to give it higher priority than subprocesses */
4776
b89a415a 4777 if (read_kbd != 0)
6ed6233b 4778 {
a2fab450 4779 int old_timers_run = timers_run;
c88164fe 4780 struct buffer *old_buffer = current_buffer;
c0323133 4781 Lisp_Object old_window = selected_window;
a2fab450 4782 int leave = 0;
177c0ea7 4783
5d6c2aa3 4784 if (detect_input_pending_run_timers (do_display))
a2fab450
GM
4785 {
4786 swallow_events (do_display);
4787 if (detect_input_pending_run_timers (do_display))
4788 leave = 1;
4789 }
6ed6233b 4790
a2fab450
GM
4791 /* If a timer has run, this might have changed buffers
4792 an alike. Make read_key_sequence aware of that. */
4793 if (timers_run != old_timers_run
c88164fe 4794 && waiting_for_user_input_p == -1
c0323133
GM
4795 && (old_buffer != current_buffer
4796 || !EQ (old_window, selected_window)))
a2fab450
GM
4797 record_asynch_buffer_change ();
4798
4799 if (leave)
4800 break;
177c0ea7
JB
4801 }
4802
69645afc 4803 /* If there is unread keyboard input, also return. */
b89a415a 4804 if (read_kbd != 0
69645afc
RS
4805 && requeued_events_pending_p ())
4806 break;
4807
77e1b3d4
RS
4808 /* If we are not checking for keyboard input now,
4809 do process events (but don't run any timers).
4810 This is so that X events will be processed.
0c9960e9 4811 Otherwise they may have to wait until polling takes place.
77e1b3d4
RS
4812 That would causes delays in pasting selections, for example.
4813
4814 (We used to do this only if wait_for_cell.) */
b89a415a 4815 if (read_kbd == 0 && detect_input_pending ())
f854a00b
RS
4816 {
4817 swallow_events (do_display);
0c9960e9 4818#if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
f854a00b
RS
4819 if (detect_input_pending ())
4820 break;
5d5beb62 4821#endif
0c9960e9 4822 }
f854a00b 4823
84aa3ace 4824 /* Exit now if the cell we're waiting for became non-nil. */
f3fbd155 4825 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
84aa3ace
RS
4826 break;
4827
4746118a 4828#ifdef SIGIO
5d5beb62 4829 /* If we think we have keyboard input waiting, but didn't get SIGIO,
d0d6b7c5
JB
4830 go read it. This can happen with X on BSD after logging out.
4831 In that case, there really is no input and no SIGIO,
4832 but select says there is input. */
4833
b89a415a 4834 if (read_kbd && interrupt_input
2601f59e 4835 && keyboard_bit_set (&Available) && ! noninteractive)
e643c5be 4836 kill (getpid (), SIGIO);
4746118a 4837#endif
d0d6b7c5 4838
d0d6b7c5
JB
4839 if (! wait_proc)
4840 got_some_input |= nfds > 0;
4841
32676c08
JB
4842 /* If checking input just got us a size-change event from X,
4843 obey it now if we should. */
b89a415a 4844 if (read_kbd || ! NILP (wait_for_cell))
2b653806 4845 do_pending_window_change (0);
32676c08 4846
a9f2c884 4847 /* Check for data from a process. */
dd2a17ab
KS
4848 if (no_avail || nfds == 0)
4849 continue;
4850
a9f2c884
RS
4851 /* Really FIRST_PROC_DESC should be 0 on Unix,
4852 but this is safer in the short run. */
a69281ff 4853 for (channel = 0; channel <= max_process_desc; channel++)
d0d6b7c5 4854 {
a69281ff
RS
4855 if (FD_ISSET (channel, &Available)
4856 && FD_ISSET (channel, &non_keyboard_wait_mask))
d0d6b7c5
JB
4857 {
4858 int nread;
4859
4860 /* If waiting for this channel, arrange to return as
4861 soon as no more input to be processed. No more
4862 waiting. */
4863 if (wait_channel == channel)
4864 {
a9f2c884 4865 wait_channel = -1;
d0d6b7c5
JB
4866 time_limit = -1;
4867 got_some_input = 1;
4868 }
4869 proc = chan_process[channel];
4870 if (NILP (proc))
4871 continue;
4872
e690ca94
KS
4873 /* If this is a server stream socket, accept connection. */
4874 if (EQ (XPROCESS (proc)->status, Qlisten))
4875 {
4876 server_accept_connection (proc, channel);
4877 continue;
4878 }
4879
d0d6b7c5
JB
4880 /* Read data from the process, starting with our
4881 buffered-ahead character if we have one. */
4882
4883 nread = read_process_output (proc, channel);
4884 if (nread > 0)
4885 {
4886 /* Since read_process_output can run a filter,
4887 which can call accept-process-output,
4888 don't try to read from any other processes
4889 before doing the select again. */
4890 FD_ZERO (&Available);
4891
4892 if (do_display)
3007ebfb 4893 redisplay_preserve_echo_area (12);
d0d6b7c5
JB
4894 }
4895#ifdef EWOULDBLOCK
4896 else if (nread == -1 && errno == EWOULDBLOCK)
4897 ;
0b75e9a4 4898#endif
89d7280d
RS
4899 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4900 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
d0d6b7c5
JB
4901#ifdef O_NONBLOCK
4902 else if (nread == -1 && errno == EAGAIN)
4903 ;
4904#else
4905#ifdef O_NDELAY
4906 else if (nread == -1 && errno == EAGAIN)
4907 ;
4908 /* Note that we cannot distinguish between no input
4909 available now and a closed pipe.
4910 With luck, a closed pipe will be accompanied by
4911 subprocess termination and SIGCHLD. */
d888760c 4912 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
d0d6b7c5 4913 ;
4740825c
KS
4914#endif /* O_NDELAY */
4915#endif /* O_NONBLOCK */
d0d6b7c5
JB
4916#ifdef HAVE_PTYS
4917 /* On some OSs with ptys, when the process on one end of
4918 a pty exits, the other end gets an error reading with
4919 errno = EIO instead of getting an EOF (0 bytes read).
4920 Therefore, if we get an error reading and errno =
4921 EIO, just continue, because the child process has
4922 exited and should clean itself up soon (e.g. when we
5651af6d
RS
4923 get a SIGCHLD).
4924
4925 However, it has been known to happen that the SIGCHLD
4740825c 4926 got lost. So raise the signal again just in case.
5651af6d 4927 It can't hurt. */
d0d6b7c5 4928 else if (nread == -1 && errno == EIO)
4740825c 4929 {
a70d5371 4930 /* Clear the descriptor now, so we only raise the
42371deb 4931 signal once. Don't do this if `process' is only
a70d5371
NR
4932 a pty. */
4933 if (XPROCESS (proc)->pid != -2)
4934 {
4935 FD_CLR (channel, &input_wait_mask);
4936 FD_CLR (channel, &non_keyboard_wait_mask);
4740825c 4937
a70d5371
NR
4938 kill (getpid (), SIGCHLD);
4939 }
4740825c
KS
4940 }
4941#endif /* HAVE_PTYS */
ffd56f97
JB
4942 /* If we can detect process termination, don't consider the process
4943 gone just because its pipe is closed. */
d0d6b7c5 4944#ifdef SIGCHLD
d888760c 4945 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
d0d6b7c5
JB
4946 ;
4947#endif
4948 else
4949 {
4950 /* Preserve status of processes already terminated. */
60f0fb11 4951 XPROCESS (proc)->tick = ++process_tick;
d0d6b7c5 4952 deactivate_process (proc);
6bfd98e7 4953 if (XPROCESS (proc)->raw_status_new)
d0d6b7c5
JB
4954 update_status (XPROCESS (proc));
4955 if (EQ (XPROCESS (proc)->status, Qrun))
4956 XPROCESS (proc)->status
4957 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4958 }
4959 }
177c0ea7 4960#ifdef NON_BLOCKING_CONNECT
1566f511
KS
4961 if (check_connect && FD_ISSET (channel, &Connecting)
4962 && FD_ISSET (channel, &connect_wait_mask))
dd2a17ab
KS
4963 {
4964 struct Lisp_Process *p;
dd2a17ab
KS
4965
4966 FD_CLR (channel, &connect_wait_mask);
4967 if (--num_pending_connects < 0)
4968 abort ();
4969
4970 proc = chan_process[channel];
4971 if (NILP (proc))
4972 continue;
4973
4974 p = XPROCESS (proc);
4975
4976#ifdef GNU_LINUX
4977 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
63136da6 4978 So only use it on systems where it is known to work. */
dd2a17ab 4979 {
ed3751c8
JB
4980 int xlen = sizeof (xerrno);
4981 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
dd2a17ab
KS
4982 xerrno = errno;
4983 }
4984#else
44c887be
PJ
4985 {
4986 struct sockaddr pname;
ed3751c8 4987 int pnamelen = sizeof (pname);
44c887be
PJ
4988
4989 /* If connection failed, getpeername will fail. */
4990 xerrno = 0;
ed3751c8 4991 if (getpeername (channel, &pname, &pnamelen) < 0)
44c887be
PJ
4992 {
4993 /* Obtain connect failure code through error slippage. */
4994 char dummy;
dd2a17ab 4995 xerrno = errno;
ed3751c8 4996 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
44c887be
PJ
4997 xerrno = errno;
4998 }
4999 }
dd2a17ab
KS
5000#endif
5001 if (xerrno)
5002 {
60f0fb11 5003 p->tick = ++process_tick;
dd2a17ab
KS
5004 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5005 deactivate_process (proc);
5006 }
5007 else
5008 {
5009 p->status = Qrun;
5010 /* Execute the sentinel here. If we had relied on
5011 status_notify to do it later, it will read input
5012 from the process before calling the sentinel. */
5013 exec_sentinel (proc, build_string ("open\n"));
e690ca94 5014 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
dd2a17ab 5015 {
60f0fb11
SM
5016 FD_SET (p->infd, &input_wait_mask);
5017 FD_SET (p->infd, &non_keyboard_wait_mask);
dd2a17ab
KS
5018 }
5019 }
5020 }
5021#endif /* NON_BLOCKING_CONNECT */
ffd56f97
JB
5022 } /* end for each file descriptor */
5023 } /* end while exit conditions not met */
d0d6b7c5 5024
2beb96f9 5025 unbind_to (count, Qnil);
d430ee71 5026
ffd56f97
JB
5027 /* If calling from keyboard input, do not quit
5028 since we want to return C-g as an input character.
5029 Otherwise, do pending quit if requested. */
b89a415a 5030 if (read_kbd >= 0)
ffd56f97
JB
5031 {
5032 /* Prevent input_pending from remaining set if we quit. */
5033 clear_input_pending ();
5034 QUIT;
5035 }
efa2a55c 5036
d0d6b7c5
JB
5037 return got_some_input;
5038}
5039\f
3b9a3dfa
RS
5040/* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5041
5042static Lisp_Object
d3da34e0 5043read_process_output_call (Lisp_Object fun_and_args)
3b9a3dfa 5044{
70949dac 5045 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
3b9a3dfa
RS
5046}
5047
5048static Lisp_Object
d3da34e0 5049read_process_output_error_handler (Lisp_Object error)
3b9a3dfa
RS
5050{
5051 cmd_error_internal (error, "error in process filter: ");
5052 Vinhibit_quit = Qt;
5053 update_echo_area ();
833ba342 5054 Fsleep_for (make_number (2), Qnil);
8c983bf2 5055 return Qt;
3b9a3dfa
RS
5056}
5057
d0d6b7c5
JB
5058/* Read pending output from the process channel,
5059 starting with our buffered-ahead character if we have one.
0fa1789e 5060 Yield number of decoded characters read.
d0d6b7c5 5061
116c423c 5062 This function reads at most 4096 characters.
d0d6b7c5 5063 If you want to read all available subprocess output,
0fa1789e
KH
5064 you must call it repeatedly until it returns zero.
5065
5066 The characters read are decoded according to PROC's coding-system
5067 for decoding. */
d0d6b7c5 5068
ff6daed3 5069static int
d3da34e0 5070read_process_output (Lisp_Object proc, register int channel)
d0d6b7c5 5071{
8f924df7 5072 register int nbytes;
d0d6b7c5 5073 char *chars;
d0d6b7c5 5074 register Lisp_Object outstream;
d0d6b7c5
JB
5075 register struct Lisp_Process *p = XPROCESS (proc);
5076 register int opoint;
c7580538 5077 struct coding_system *coding = proc_decode_coding_system[channel];
60f0fb11 5078 int carryover = p->decoding_carryover;
116c423c 5079 int readmax = 4096;
3a4fa2f2
SM
5080 int count = SPECPDL_INDEX ();
5081 Lisp_Object odeactivate;
d0d6b7c5 5082
e690ca94 5083 chars = (char *) alloca (carryover + readmax);
e7fbaa65
KH
5084 if (carryover)
5085 /* See the comment above. */
72af86bd 5086 memcpy (chars, SDATA (p->decoding_buf), carryover);
0fa1789e 5087
e690ca94
KS
5088#ifdef DATAGRAM_SOCKETS
5089 /* We have a working select, so proc_buffered_char is always -1. */
5090 if (DATAGRAM_CHAN_P (channel))
5091 {
5092 int len = datagram_address[channel].len;
39b1da20 5093 nbytes = recvfrom (channel, chars + carryover, readmax,
e690ca94
KS
5094 0, datagram_address[channel].sa, &len);
5095 }
5096 else
5097#endif
d0d6b7c5 5098 if (proc_buffered_char[channel] < 0)
6b61353c 5099 {
39b1da20 5100 nbytes = emacs_read (channel, chars + carryover, readmax);
6b61353c 5101#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11 5102 if (nbytes > 0 && p->adaptive_read_buffering)
6b61353c 5103 {
60f0fb11 5104 int delay = p->read_output_delay;
6b61353c
KH
5105 if (nbytes < 256)
5106 {
5107 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5108 {
5109 if (delay == 0)
5110 process_output_delay_count++;
5111 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5112 }
5113 }
39b1da20 5114 else if (delay > 0 && (nbytes == readmax))
6b61353c
KH
5115 {
5116 delay -= READ_OUTPUT_DELAY_INCREMENT;
5117 if (delay == 0)
5118 process_output_delay_count--;
5119 }
60f0fb11 5120 p->read_output_delay = delay;
6b61353c
KH
5121 if (delay)
5122 {
60f0fb11 5123 p->read_output_skip = 1;
6b61353c
KH
5124 process_output_skip = 1;
5125 }
5126 }
5127#endif
5128 }
d0d6b7c5
JB
5129 else
5130 {
ed7a4b2d 5131 chars[carryover] = proc_buffered_char[channel];
d0d6b7c5 5132 proc_buffered_char[channel] = -1;
39b1da20 5133 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
1d2fc612
RS
5134 if (nbytes < 0)
5135 nbytes = 1;
d0d6b7c5 5136 else
1d2fc612 5137 nbytes = nbytes + 1;
d0d6b7c5 5138 }
d0d6b7c5 5139
60f0fb11 5140 p->decoding_carryover = 0;
ca65341e 5141
ed7a4b2d 5142 /* At this point, NBYTES holds number of bytes just received
0fa1789e 5143 (including the one in proc_buffered_char[channel]). */
de7fbd09
KH
5144 if (nbytes <= 0)
5145 {
5146 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5147 return nbytes;
5148 coding->mode |= CODING_MODE_LAST_BLOCK;
5149 }
d0d6b7c5 5150
1d2fc612 5151 /* Now set NBYTES how many bytes we must decode. */
e7fbaa65 5152 nbytes += carryover;
0fa1789e 5153
3a4fa2f2
SM
5154 odeactivate = Vdeactivate_mark;
5155 /* There's no good reason to let process filters change the current
5156 buffer, and many callers of accept-process-output, sit-for, and
5157 friends don't expect current-buffer to be changed from under them. */
d2630aef 5158 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
3a4fa2f2 5159
1d2fc612 5160 /* Read and dispose of the process output. */
d0d6b7c5
JB
5161 outstream = p->filter;
5162 if (!NILP (outstream))
5163 {
dfc21838 5164 Lisp_Object obuffer, okeymap;
1d2fc612 5165 Lisp_Object text;
4da2f5be 5166 int outer_running_asynch_code = running_asynch_code;
bbce7d72 5167 int waiting = waiting_for_user_input_p;
30c78175 5168
dfc21838
RS
5169 /* No need to gcpro these, because all we do with them later
5170 is test them for EQness, and none of them should be a string. */
dfc21838
RS
5171 XSETBUFFER (obuffer, current_buffer);
5172 okeymap = current_buffer->keymap;
30c78175 5173
3a4fa2f2
SM
5174 /* We inhibit quit here instead of just catching it so that
5175 hitting ^G when a filter happens to be running won't screw
5176 it up. */
d0d6b7c5 5177 specbind (Qinhibit_quit, Qt);
6545aada 5178 specbind (Qlast_nonmenu_event, Qt);
3b9a3dfa 5179
4da2f5be
RS
5180 /* In case we get recursively called,
5181 and we already saved the match data nonrecursively,
5182 save the same match data in safely recursive fashion. */
5183 if (outer_running_asynch_code)
5184 {
5185 Lisp_Object tem;
5186 /* Don't clobber the CURRENT match data, either! */
89f2614d
KS
5187 tem = Fmatch_data (Qnil, Qnil, Qnil);
5188 restore_search_regs ();
5189 record_unwind_save_match_data ();
5190 Fset_match_data (tem, Qt);
4da2f5be
RS
5191 }
5192
5193 /* For speed, if a search happens within this code,
5194 save the match data in a special nonrecursive fashion. */
7074fde6 5195 running_asynch_code = 1;
4da2f5be 5196
5bbf78c1
KH
5197 decode_coding_c_string (coding, chars, nbytes, Qt);
5198 text = coding->dst_object;
5bbf78c1 5199 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
ed7a4b2d 5200 /* A new coding system might be found. */
5bbf78c1 5201 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
ed7a4b2d 5202 {
5bbf78c1 5203 p->decode_coding_system = Vlast_coding_system_used;
ed7a4b2d
KH
5204
5205 /* Don't call setup_coding_system for
5206 proc_decode_coding_system[channel] here. It is done in
5207 detect_coding called via decode_coding above. */
5208
5209 /* If a coding system for encoding is not yet decided, we set
5210 it as the same as coding-system for decoding.
5211
5212 But, before doing that we must check if
5213 proc_encode_coding_system[p->outfd] surely points to a
5214 valid memory because p->outfd will be changed once EOF is
5215 sent to the process. */
5216 if (NILP (p->encode_coding_system)
60f0fb11 5217 && proc_encode_coding_system[p->outfd])
ed7a4b2d 5218 {
76d812bb
KH
5219 p->encode_coding_system
5220 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5bbf78c1 5221 setup_coding_system (p->encode_coding_system,
60f0fb11 5222 proc_encode_coding_system[p->outfd]);
ed7a4b2d
KH
5223 }
5224 }
51c6067d 5225
dd8c7a53
KH
5226 if (coding->carryover_bytes > 0)
5227 {
04961398
KH
5228 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5229 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
72af86bd
AS
5230 memcpy (SDATA (p->decoding_buf), coding->carryover,
5231 coding->carryover_bytes);
8c406a9b 5232 p->decoding_carryover = coding->carryover_bytes;
dd8c7a53 5233 }
e430e5ba 5234 if (SBYTES (text) > 0)
dd97db06
KH
5235 internal_condition_case_1 (read_process_output_call,
5236 Fcons (outstream,
5237 Fcons (proc, Fcons (text, Qnil))),
5238 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5239 read_process_output_error_handler);
4da2f5be
RS
5240
5241 /* If we saved the match data nonrecursively, restore it now. */
89f2614d 5242 restore_search_regs ();
4da2f5be 5243 running_asynch_code = outer_running_asynch_code;
d0d6b7c5 5244
bbce7d72
RS
5245 /* Restore waiting_for_user_input_p as it was
5246 when we were called, in case the filter clobbered it. */
5247 waiting_for_user_input_p = waiting;
5248
7973cfa8
RS
5249#if 0 /* Call record_asynch_buffer_change unconditionally,
5250 because we might have changed minor modes or other things
5251 that affect key bindings. */
dfc21838
RS
5252 if (! EQ (Fcurrent_buffer (), obuffer)
5253 || ! EQ (current_buffer->keymap, okeymap))
7973cfa8 5254#endif
927e08be
RS
5255 /* But do it only if the caller is actually going to read events.
5256 Otherwise there's no need to make him wake up, and it could
7157b8fe 5257 cause trouble (for example it would make sit_for return). */
927e08be
RS
5258 if (waiting_for_user_input_p == -1)
5259 record_asynch_buffer_change ();
d0d6b7c5
JB
5260 }
5261
5262 /* If no filter, write into buffer if it isn't dead. */
3a4fa2f2 5263 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
d0d6b7c5 5264 {
b0310da4 5265 Lisp_Object old_read_only;
12ca5cdf 5266 int old_begv, old_zv;
d8a2934e 5267 int old_begv_byte, old_zv_byte;
d8a2934e
RS
5268 int before, before_byte;
5269 int opoint_byte;
ed7a4b2d 5270 Lisp_Object text;
926b7e5e 5271 struct buffer *b;
30c78175 5272
d0d6b7c5 5273 Fset_buffer (p->buffer);
6ec8bbd2 5274 opoint = PT;
d8a2934e 5275 opoint_byte = PT_BYTE;
b0310da4 5276 old_read_only = current_buffer->read_only;
12ca5cdf
RS
5277 old_begv = BEGV;
5278 old_zv = ZV;
d8a2934e
RS
5279 old_begv_byte = BEGV_BYTE;
5280 old_zv_byte = ZV_BYTE;
b0310da4
JB
5281
5282 current_buffer->read_only = Qnil;
d0d6b7c5
JB
5283
5284 /* Insert new output into buffer
5285 at the current end-of-output marker,
5286 thus preserving logical ordering of input and output. */
5287 if (XMARKER (p->mark)->buffer)
d8a2934e
RS
5288 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5289 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5290 ZV_BYTE));
d0d6b7c5 5291 else
d8a2934e 5292 SET_PT_BOTH (ZV, ZV_BYTE);
12ca5cdf 5293 before = PT;
d8a2934e 5294 before_byte = PT_BYTE;
b0310da4
JB
5295
5296 /* If the output marker is outside of the visible region, save
5297 the restriction and widen. */
6ec8bbd2 5298 if (! (BEGV <= PT && PT <= ZV))
b0310da4
JB
5299 Fwiden ();
5300
5bbf78c1
KH
5301 decode_coding_c_string (coding, chars, nbytes, Qt);
5302 text = coding->dst_object;
5303 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
ed7a4b2d
KH
5304 /* A new coding system might be found. See the comment in the
5305 similar code in the previous `if' block. */
5bbf78c1 5306 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
ed7a4b2d 5307 {
5bbf78c1 5308 p->decode_coding_system = Vlast_coding_system_used;
ed7a4b2d 5309 if (NILP (p->encode_coding_system)
60f0fb11 5310 && proc_encode_coding_system[p->outfd])
ed7a4b2d 5311 {
76d812bb
KH
5312 p->encode_coding_system
5313 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5bbf78c1 5314 setup_coding_system (p->encode_coding_system,
60f0fb11 5315 proc_encode_coding_system[p->outfd]);
ed7a4b2d
KH
5316 }
5317 }
dd8c7a53
KH
5318 if (coding->carryover_bytes > 0)
5319 {
04961398
KH
5320 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5321 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
72af86bd
AS
5322 memcpy (SDATA (p->decoding_buf), coding->carryover,
5323 coding->carryover_bytes);
8c406a9b 5324 p->decoding_carryover = coding->carryover_bytes;
dd8c7a53 5325 }
d69864bf
KH
5326 /* Adjust the multibyteness of TEXT to that of the buffer. */
5327 if (NILP (current_buffer->enable_multibyte_characters)
5328 != ! STRING_MULTIBYTE (text))
5329 text = (STRING_MULTIBYTE (text)
57bb5c37 5330 ? Fstring_as_unibyte (text)
03f04413 5331 : Fstring_to_multibyte (text));
57bb5c37
KH
5332 /* Insert before markers in case we are inserting where
5333 the buffer's mark is, and the user's next command is Meta-y. */
e430e5ba
KH
5334 insert_from_string_before_markers (text, 0, 0,
5335 SCHARS (text), SBYTES (text), 0);
0d023da1 5336
926b7e5e
GM
5337 /* Make sure the process marker's position is valid when the
5338 process buffer is changed in the signal_after_change above.
5339 W3 is known to do that. */
5340 if (BUFFERP (p->buffer)
5341 && (b = XBUFFER (p->buffer), b != current_buffer))
5342 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5343 else
5344 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
b0310da4 5345
d0d6b7c5
JB
5346 update_mode_lines++;
5347
12ca5cdf
RS
5348 /* Make sure opoint and the old restrictions
5349 float ahead of any new text just as point would. */
5350 if (opoint >= before)
d8a2934e
RS
5351 {
5352 opoint += PT - before;
5353 opoint_byte += PT_BYTE - before_byte;
5354 }
12ca5cdf 5355 if (old_begv > before)
d8a2934e
RS
5356 {
5357 old_begv += PT - before;
5358 old_begv_byte += PT_BYTE - before_byte;
5359 }
12ca5cdf 5360 if (old_zv >= before)
d8a2934e
RS
5361 {
5362 old_zv += PT - before;
5363 old_zv_byte += PT_BYTE - before_byte;
5364 }
12ca5cdf 5365
b0310da4 5366 /* If the restriction isn't what it should be, set it. */
12ca5cdf
RS
5367 if (old_begv != BEGV || old_zv != ZV)
5368 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
b0310da4 5369
30c78175 5370
b0310da4 5371 current_buffer->read_only = old_read_only;
d8a2934e 5372 SET_PT_BOTH (opoint, opoint_byte);
d0d6b7c5 5373 }
3a4fa2f2
SM
5374 /* Handling the process output should not deactivate the mark. */
5375 Vdeactivate_mark = odeactivate;
5376
5377 unbind_to (count, Qnil);
1d2fc612 5378 return nbytes;
d0d6b7c5 5379}
d0d6b7c5
JB
5380\f
5381/* Sending data to subprocess */
5382
5383jmp_buf send_process_frame;
0daad115 5384Lisp_Object process_sent_to;
d0d6b7c5
JB
5385
5386SIGTYPE
d3da34e0 5387send_process_trap (int ignore)
d0d6b7c5 5388{
333f1b6f 5389 SIGNAL_THREAD_CHECK (SIGPIPE);
c8f44005 5390 sigunblock (sigmask (SIGPIPE));
d0d6b7c5
JB
5391 longjmp (send_process_frame, 1);
5392}
5393
4556b700
RS
5394/* Send some data to process PROC.
5395 BUF is the beginning of the data; LEN is the number of characters.
a92e4183
KH
5396 OBJECT is the Lisp object that the data comes from. If OBJECT is
5397 nil or t, it means that the data comes from C string.
0fa1789e 5398
a92e4183
KH
5399 If OBJECT is not nil, the data is encoded by PROC's coding-system
5400 for encoding before it is sent.
1fb0098c
GM
5401
5402 This function can evaluate Lisp code and can garbage collect. */
4556b700 5403
ff6daed3 5404static void
8ea90aa3 5405send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
d3da34e0 5406 volatile int len, volatile Lisp_Object object)
d0d6b7c5 5407{
ecd1f654 5408 /* Use volatile to protect variables from being clobbered by longjmp. */
6b61353c 5409 struct Lisp_Process *p = XPROCESS (proc);
d0d6b7c5 5410 int rv;
0fa1789e 5411 struct coding_system *coding;
347f3cd3 5412 struct gcpro gcpro1;
d2aa42f8 5413 SIGTYPE (*volatile old_sigpipe) (int);
6044e593 5414
347f3cd3 5415 GCPRO1 (object);
d0d6b7c5 5416
6bfd98e7 5417 if (p->raw_status_new)
6b61353c
KH
5418 update_status (p);
5419 if (! EQ (p->status, Qrun))
5420 error ("Process %s not running", SDATA (p->name));
60f0fb11 5421 if (p->outfd < 0)
6b61353c 5422 error ("Output file descriptor of %s is closed", SDATA (p->name));
0fa1789e 5423
60f0fb11 5424 coding = proc_encode_coding_system[p->outfd];
5bbf78c1 5425 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
486b111b 5426
ed7a4b2d
KH
5427 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5428 || (BUFFERP (object)
a92e4183
KH
5429 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5430 || EQ (object, Qt))
278bfdd6 5431 {
6b61353c 5432 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
278bfdd6
KH
5433 /* The coding system for encoding was changed to raw-text
5434 because we sent a unibyte text previously. Now we are
5435 sending a multibyte text, thus we must encode it by the
6b61353c
KH
5436 original coding system specified for the current process. */
5437 setup_coding_system (p->encode_coding_system, coding);
e08bbb84 5438 coding->src_multibyte = 1;
278bfdd6
KH
5439 }
5440 else
5441 {
a92e4183
KH
5442 /* For sending a unibyte text, character code conversion should
5443 not take place but EOL conversion should. So, setup raw-text
5444 or one of the subsidiary if we have not yet done it. */
5bbf78c1 5445 if (CODING_REQUIRE_ENCODING (coding))
a92e4183
KH
5446 {
5447 if (CODING_REQUIRE_FLUSHING (coding))
5448 {
5449 /* But, before changing the coding, we must flush out data. */
5450 coding->mode |= CODING_MODE_LAST_BLOCK;
5451 send_process (proc, "", 0, Qt);
8f924df7 5452 coding->mode &= CODING_MODE_LAST_BLOCK;
a92e4183 5453 }
5bbf78c1
KH
5454 setup_coding_system (raw_text_coding_system
5455 (Vlast_coding_system_used),
5456 coding);
e08bbb84 5457 coding->src_multibyte = 0;
a92e4183 5458 }
278bfdd6 5459 }
a4a37e65
KH
5460 coding->dst_multibyte = 0;
5461
ed7a4b2d 5462 if (CODING_REQUIRE_ENCODING (coding))
0fa1789e 5463 {
5bbf78c1 5464 coding->dst_object = Qt;
ed7a4b2d 5465 if (BUFFERP (object))
0fa1789e 5466 {
5bbf78c1
KH
5467 int from_byte, from, to;
5468 int save_pt, save_pt_byte;
5469 struct buffer *cur = current_buffer;
5470
5471 set_buffer_internal (XBUFFER (object));
5472 save_pt = PT, save_pt_byte = PT_BYTE;
5473
5474 from_byte = PTR_BYTE_POS (buf);
5475 from = BYTE_TO_CHAR (from_byte);
5476 to = BYTE_TO_CHAR (from_byte + len);
5477 TEMP_SET_PT_BOTH (from, from_byte);
5478 encode_coding_object (coding, object, from, from_byte,
5479 to, from_byte + len, Qt);
5480 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5481 set_buffer_internal (cur);
ed7a4b2d
KH
5482 }
5483 else if (STRINGP (object))
5484 {
550c8289
KH
5485 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5486 SBYTES (object), Qt);
0fa1789e 5487 }
5bbf78c1 5488 else
452294c2 5489 {
5bbf78c1
KH
5490 coding->dst_object = make_unibyte_string (buf, len);
5491 coding->produced = len;
452294c2 5492 }
ed7a4b2d 5493
e7fbaa65 5494 len = coding->produced;
347f3cd3
AS
5495 object = coding->dst_object;
5496 buf = SDATA (object);
0fa1789e 5497 }
d0d6b7c5 5498
4556b700
RS
5499 if (pty_max_bytes == 0)
5500 {
5501#if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
60f0fb11 5502 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
4556b700
RS
5503 if (pty_max_bytes < 0)
5504 pty_max_bytes = 250;
5505#else
5506 pty_max_bytes = 250;
5507#endif
5508 /* Deduct one, to leave space for the eof. */
5509 pty_max_bytes--;
5510 }
5511
0daad115
GM
5512 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5513 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5514 when returning with longjmp despite being declared volatile. */
d0d6b7c5 5515 if (!setjmp (send_process_frame))
0daad115
GM
5516 {
5517 process_sent_to = proc;
5518 while (len > 0)
5519 {
5520 int this = len;
93b4f699 5521
0daad115
GM
5522 /* Send this batch, using one or more write calls. */
5523 while (this > 0)
5524 {
60f0fb11 5525 int outfd = p->outfd;
d2aa42f8 5526 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
e690ca94
KS
5527#ifdef DATAGRAM_SOCKETS
5528 if (DATAGRAM_CHAN_P (outfd))
5529 {
5530 rv = sendto (outfd, (char *) buf, this,
5531 0, datagram_address[outfd].sa,
5532 datagram_address[outfd].len);
5533 if (rv < 0 && errno == EMSGSIZE)
c8f44005
RS
5534 {
5535 signal (SIGPIPE, old_sigpipe);
5536 report_file_error ("sending datagram",
5537 Fcons (proc, Qnil));
5538 }
e690ca94
KS
5539 }
5540 else
5541#endif
6b61353c
KH
5542 {
5543 rv = emacs_write (outfd, (char *) buf, this);
5544#ifdef ADAPTIVE_READ_BUFFERING
60f0fb11
SM
5545 if (p->read_output_delay > 0
5546 && p->adaptive_read_buffering == 1)
6b61353c 5547 {
60f0fb11 5548 p->read_output_delay = 0;
6b61353c 5549 process_output_delay_count--;
60f0fb11 5550 p->read_output_skip = 0;
6b61353c
KH
5551 }
5552#endif
5553 }
0daad115 5554 signal (SIGPIPE, old_sigpipe);
4556b700 5555
0daad115
GM
5556 if (rv < 0)
5557 {
5558 if (0
d0d6b7c5 5559#ifdef EWOULDBLOCK
0daad115 5560 || errno == EWOULDBLOCK
d0d6b7c5
JB
5561#endif
5562#ifdef EAGAIN
0daad115 5563 || errno == EAGAIN
d0d6b7c5 5564#endif
0daad115 5565 )
177c0ea7 5566 /* Buffer is full. Wait, accepting input;
0daad115
GM
5567 that may allow the program
5568 to finish doing output and read more. */
5569 {
0daad115 5570 int offset = 0;
4556b700 5571
3433b6bd 5572#ifdef BROKEN_PTY_READ_AFTER_EAGAIN
0daad115
GM
5573 /* A gross hack to work around a bug in FreeBSD.
5574 In the following sequence, read(2) returns
5575 bogus data:
5576
5577 write(2) 1022 bytes
5578 write(2) 954 bytes, get EAGAIN
5579 read(2) 1024 bytes in process_read_output
5580 read(2) 11 bytes in process_read_output
5581
5582 That is, read(2) returns more bytes than have
5583 ever been written successfully. The 1033 bytes
5584 read are the 1022 bytes written successfully
5585 after processing (for example with CRs added if
5586 the terminal is set up that way which it is
5587 here). The same bytes will be seen again in a
5588 later read(2), without the CRs. */
177c0ea7 5589
0daad115
GM
5590 if (errno == EAGAIN)
5591 {
5592 int flags = FWRITE;
60f0fb11 5593 ioctl (p->outfd, TIOCFLUSH, &flags);
0daad115 5594 }
3433b6bd 5595#endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
177c0ea7 5596
0daad115
GM
5597 /* Running filters might relocate buffers or strings.
5598 Arrange to relocate BUF. */
347f3cd3 5599 if (BUFFERP (object))
0daad115
GM
5600 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5601 else if (STRINGP (object))
d5db4077 5602 offset = buf - SDATA (object);
0daad115 5603
f3e6605c 5604#ifdef EMACS_HAS_USECS
214d6069 5605 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
f3e6605c 5606#else
214d6069 5607 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
f3e6605c 5608#endif
4556b700 5609
347f3cd3 5610 if (BUFFERP (object))
0daad115
GM
5611 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5612 else if (STRINGP (object))
d5db4077 5613 buf = offset + SDATA (object);
4556b700 5614
0daad115
GM
5615 rv = 0;
5616 }
5617 else
5618 /* This is a real error. */
5619 report_file_error ("writing to process", Fcons (proc, Qnil));
5620 }
5621 buf += rv;
5622 len -= rv;
5623 this -= rv;
5624 }
0daad115
GM
5625 }
5626 }
d0d6b7c5
JB
5627 else
5628 {
0ff69270 5629 signal (SIGPIPE, old_sigpipe);
0daad115 5630 proc = process_sent_to;
6b61353c 5631 p = XPROCESS (proc);
6bfd98e7 5632 p->raw_status_new = 0;
6b61353c 5633 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
60f0fb11 5634 p->tick = ++process_tick;
d0d6b7c5 5635 deactivate_process (proc);
6b61353c 5636 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
d0d6b7c5 5637 }
6044e593
RS
5638
5639 UNGCPRO;
d0d6b7c5
JB
5640}
5641
5642DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
fdb82f93
PJ
5643 3, 3, 0,
5644 doc: /* Send current contents of region as input to PROCESS.
5645PROCESS may be a process, a buffer, the name of a process or buffer, or
5646nil, indicating the current buffer's process.
5647Called from program, takes three arguments, PROCESS, START and END.
5648If the region is more than 500 characters long,
5649it is sent in several bunches. This may happen even for shorter regions.
5650Output from processes can arrive in between bunches. */)
5842a27b 5651 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
d0d6b7c5
JB
5652{
5653 Lisp_Object proc;
1b234f64 5654 int start1, end1;
d0d6b7c5
JB
5655
5656 proc = get_process (process);
5657 validate_region (&start, &end);
1b234f64
KH
5658
5659 if (XINT (start) < GPT && XINT (end) > GPT)
5660 move_gap (XINT (start));
5661
5662 start1 = CHAR_TO_BYTE (XINT (start));
5663 end1 = CHAR_TO_BYTE (XINT (end));
5664 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5665 Fcurrent_buffer ());
5666
d0d6b7c5
JB
5667 return Qnil;
5668}
5669
5670DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
fdb82f93
PJ
5671 2, 2, 0,
5672 doc: /* Send PROCESS the contents of STRING as input.
5673PROCESS may be a process, a buffer, the name of a process or buffer, or
5674nil, indicating the current buffer's process.
5675If STRING is more than 500 characters long,
5676it is sent in several bunches. This may happen even for shorter strings.
5677Output from processes can arrive in between bunches. */)
5842a27b 5678 (Lisp_Object process, Lisp_Object string)
d0d6b7c5
JB
5679{
5680 Lisp_Object proc;
b7826503 5681 CHECK_STRING (string);
d0d6b7c5 5682 proc = get_process (process);
1b234f64
KH
5683 send_process (proc, SDATA (string),
5684 SBYTES (string), string);
d0d6b7c5
JB
5685 return Qnil;
5686}
5687\f
16782258
JD
5688/* Return the foreground process group for the tty/pty that
5689 the process P uses. */
5690static int
d3da34e0 5691emacs_get_tty_pgrp (struct Lisp_Process *p)
16782258
JD
5692{
5693 int gid = -1;
5694
f3d9532b 5695#ifdef TIOCGPGRP
60f0fb11 5696 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
16782258
JD
5697 {
5698 int fd;
5699 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5700 master side. Try the slave side. */
eef60308 5701 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
16782258
JD
5702
5703 if (fd != -1)
5704 {
5705 ioctl (fd, TIOCGPGRP, &gid);
5706 emacs_close (fd);
5707 }
5708 }
5709#endif /* defined (TIOCGPGRP ) */
5710
5711 return gid;
5712}
5713
b81ea5ef
RS
5714DEFUN ("process-running-child-p", Fprocess_running_child_p,
5715 Sprocess_running_child_p, 0, 1, 0,
fdb82f93
PJ
5716 doc: /* Return t if PROCESS has given the terminal to a child.
5717If the operating system does not make it possible to find out,
5718return t unconditionally. */)
5842a27b 5719 (Lisp_Object process)
b81ea5ef
RS
5720{
5721 /* Initialize in case ioctl doesn't exist or gives an error,
5722 in a way that will cause returning t. */
16782258 5723 int gid;
b81ea5ef
RS
5724 Lisp_Object proc;
5725 struct Lisp_Process *p;
5726
5727 proc = get_process (process);
5728 p = XPROCESS (proc);
5729
d888760c 5730 if (!EQ (p->type, Qreal))
b81ea5ef 5731 error ("Process %s is not a subprocess",
d5db4077 5732 SDATA (p->name));
60f0fb11 5733 if (p->infd < 0)
b81ea5ef 5734 error ("Process %s is not active",
d5db4077 5735 SDATA (p->name));
b81ea5ef 5736
16782258 5737 gid = emacs_get_tty_pgrp (p);
b81ea5ef 5738
6bfd98e7 5739 if (gid == p->pid)
b81ea5ef
RS
5740 return Qnil;
5741 return Qt;
5742}
5743\f
d0d6b7c5 5744/* send a signal number SIGNO to PROCESS.
b81ea5ef
RS
5745 If CURRENT_GROUP is t, that means send to the process group
5746 that currently owns the terminal being used to communicate with PROCESS.
d0d6b7c5 5747 This is used for various commands in shell mode.
b81ea5ef
RS
5748 If CURRENT_GROUP is lambda, that means send to the process group
5749 that currently owns the terminal, but only if it is NOT the shell itself.
5750
d0d6b7c5 5751 If NOMSG is zero, insert signal-announcements into process's buffers
b0310da4
JB
5752 right away.
5753
5754 If we can, we try to signal PROCESS by sending control characters
e333e864 5755 down the pty. This allows us to signal inferiors who have changed
b0310da4 5756 their uid, for which killpg would return an EPERM error. */
d0d6b7c5 5757
f9738840 5758static void
d3da34e0
JB
5759process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5760 int nomsg)
d0d6b7c5
JB
5761{
5762 Lisp_Object proc;
5763 register struct Lisp_Process *p;
5764 int gid;
5765 int no_pgrp = 0;
5766
5767 proc = get_process (process);
5768 p = XPROCESS (proc);
5769
d888760c 5770 if (!EQ (p->type, Qreal))
d0d6b7c5 5771 error ("Process %s is not a subprocess",
d5db4077 5772 SDATA (p->name));
60f0fb11 5773 if (p->infd < 0)
d0d6b7c5 5774 error ("Process %s is not active",
d5db4077 5775 SDATA (p->name));
d0d6b7c5 5776
60f0fb11 5777 if (!p->pty_flag)
d0d6b7c5
JB
5778 current_group = Qnil;
5779
d0d6b7c5 5780 /* If we are using pgrps, get a pgrp number and make it negative. */
2af70a0c
RS
5781 if (NILP (current_group))
5782 /* Send the signal to the shell's process group. */
6bfd98e7 5783 gid = p->pid;
2af70a0c 5784 else
d0d6b7c5 5785 {
b0310da4 5786#ifdef SIGNALS_VIA_CHARACTERS
d0d6b7c5
JB
5787 /* If possible, send signals to the entire pgrp
5788 by sending an input character to it. */
b0310da4 5789
6be429b1 5790 struct termios t;
7f916a36
RS
5791 cc_t *sig_char = NULL;
5792
60f0fb11 5793 tcgetattr (p->infd, &t);
6be429b1
JB
5794
5795 switch (signo)
5796 {
5797 case SIGINT:
7f916a36
RS
5798 sig_char = &t.c_cc[VINTR];
5799 break;
6be429b1
JB
5800
5801 case SIGQUIT:
7f916a36
RS
5802 sig_char = &t.c_cc[VQUIT];
5803 break;
6be429b1
JB
5804
5805 case SIGTSTP:
d0adf46f 5806#if defined (VSWTCH) && !defined (PREFER_VSUSP)
7f916a36 5807 sig_char = &t.c_cc[VSWTCH];
6be429b1 5808#else
7f916a36 5809 sig_char = &t.c_cc[VSUSP];
6be429b1 5810#endif
7f916a36 5811 break;
6be429b1
JB
5812 }
5813
ca4313d5 5814 if (sig_char && *sig_char != CDISABLE)
f1c206fc
RS
5815 {
5816 send_process (proc, sig_char, 1, Qnil);
5817 return;
5818 }
5819 /* If we can't send the signal with a character,
5820 fall through and send it another way. */
f1c206fc
RS
5821
5822 /* The code above may fall through if it can't
5823 handle the signal. */
20505336 5824#endif /* defined (SIGNALS_VIA_CHARACTERS) */
d0d6b7c5 5825
177c0ea7 5826#ifdef TIOCGPGRP
2af70a0c 5827 /* Get the current pgrp using the tty itself, if we have that.
d0d6b7c5
JB
5828 Otherwise, use the pty to get the pgrp.
5829 On pfa systems, saka@pfu.fujitsu.co.JP writes:
b0310da4
JB
5830 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5831 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
d0d6b7c5
JB
5832 His patch indicates that if TIOCGPGRP returns an error, then
5833 we should just assume that p->pid is also the process group id. */
d0d6b7c5 5834
16782258 5835 gid = emacs_get_tty_pgrp (p);
f3d9532b 5836
16782258
JD
5837 if (gid == -1)
5838 /* If we can't get the information, assume
5839 the shell owns the tty. */
6bfd98e7 5840 gid = p->pid;
2af70a0c
RS
5841
5842 /* It is not clear whether anything really can set GID to -1.
5843 Perhaps on some system one of those ioctls can or could do so.
5844 Or perhaps this is vestigial. */
d0d6b7c5
JB
5845 if (gid == -1)
5846 no_pgrp = 1;
b0310da4 5847#else /* ! defined (TIOCGPGRP ) */
301c3fe4
JB
5848 /* Can't select pgrps on this system, so we know that
5849 the child itself heads the pgrp. */
6bfd98e7 5850 gid = p->pid;
301c3fe4 5851#endif /* ! defined (TIOCGPGRP ) */
b81ea5ef
RS
5852
5853 /* If current_group is lambda, and the shell owns the terminal,
5854 don't send any signal. */
6bfd98e7 5855 if (EQ (current_group, Qlambda) && gid == p->pid)
b81ea5ef 5856 return;
d0d6b7c5 5857 }
d0d6b7c5
JB
5858
5859 switch (signo)
5860 {
5861#ifdef SIGCONT
5862 case SIGCONT:
6bfd98e7 5863 p->raw_status_new = 0;
d0d6b7c5 5864 p->status = Qrun;
60f0fb11 5865 p->tick = ++process_tick;
d0d6b7c5 5866 if (!nomsg)
e42bdf01
CY
5867 {
5868 status_notify (NULL);
5869 redisplay_preserve_echo_area (13);
5870 }
d0d6b7c5 5871 break;
301c3fe4 5872#endif /* ! defined (SIGCONT) */
d0d6b7c5 5873 case SIGINT:
d0d6b7c5 5874 case SIGQUIT:
d0d6b7c5 5875 case SIGKILL:
60f0fb11 5876 flush_pending_output (p->infd);
d0d6b7c5
JB
5877 break;
5878 }
5879
5880 /* If we don't have process groups, send the signal to the immediate
5881 subprocess. That isn't really right, but it's better than any
5882 obvious alternative. */
5883 if (no_pgrp)
5884 {
6bfd98e7 5885 kill (p->pid, signo);
d0d6b7c5
JB
5886 return;
5887 }
5888
5889 /* gid may be a pid, or minus a pgrp's number */
5890#ifdef TIOCSIGSEND
5891 if (!NILP (current_group))
16782258 5892 {
60f0fb11 5893 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
16782258
JD
5894 EMACS_KILLPG (gid, signo);
5895 }
d0d6b7c5
JB
5896 else
5897 {
6bfd98e7 5898 gid = - p->pid;
d0d6b7c5
JB
5899 kill (gid, signo);
5900 }
301c3fe4 5901#else /* ! defined (TIOCSIGSEND) */
2af70a0c 5902 EMACS_KILLPG (gid, signo);
301c3fe4 5903#endif /* ! defined (TIOCSIGSEND) */
d0d6b7c5
JB
5904}
5905
5906DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
fdb82f93
PJ
5907 doc: /* Interrupt process PROCESS.
5908PROCESS may be a process, a buffer, or the name of a process or buffer.
f3d9532b 5909No arg or nil means current buffer's process.
fdb82f93
PJ
5910Second arg CURRENT-GROUP non-nil means send signal to
5911the current process-group of the process's controlling terminal
5912rather than to the process's own process group.
5913If the process is a shell, this means interrupt current subjob
5914rather than the shell.
5915
5916If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5917don't send the signal. */)
5842a27b 5918 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5919{
5920 process_send_signal (process, SIGINT, current_group, 0);
5921 return process;
5922}
5923
5924DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
fdb82f93
PJ
5925 doc: /* Kill process PROCESS. May be process or name of one.
5926See function `interrupt-process' for more details on usage. */)
5842a27b 5927 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5928{
5929 process_send_signal (process, SIGKILL, current_group, 0);
5930 return process;
5931}
5932
5933DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
fdb82f93
PJ
5934 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5935See function `interrupt-process' for more details on usage. */)
5842a27b 5936 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5
JB
5937{
5938 process_send_signal (process, SIGQUIT, current_group, 0);
5939 return process;
5940}
5941
5942DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
fdb82f93 5943 doc: /* Stop process PROCESS. May be process or name of one.
177c0ea7 5944See function `interrupt-process' for more details on usage.
d888760c
GM
5945If PROCESS is a network or serial process, inhibit handling of incoming
5946traffic. */)
5842a27b 5947 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5 5948{
d888760c 5949 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
e690ca94
KS
5950 {
5951 struct Lisp_Process *p;
177c0ea7 5952
e690ca94
KS
5953 p = XPROCESS (process);
5954 if (NILP (p->command)
60f0fb11 5955 && p->infd >= 0)
e690ca94 5956 {
60f0fb11
SM
5957 FD_CLR (p->infd, &input_wait_mask);
5958 FD_CLR (p->infd, &non_keyboard_wait_mask);
e690ca94
KS
5959 }
5960 p->command = Qt;
5961 return process;
5962 }
d0d6b7c5 5963#ifndef SIGTSTP
a9a73d6c 5964 error ("No SIGTSTP support");
d0d6b7c5
JB
5965#else
5966 process_send_signal (process, SIGTSTP, current_group, 0);
5967#endif
5968 return process;
5969}
5970
5971DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
fdb82f93 5972 doc: /* Continue process PROCESS. May be process or name of one.
177c0ea7 5973See function `interrupt-process' for more details on usage.
d888760c
GM
5974If PROCESS is a network or serial process, resume handling of incoming
5975traffic. */)
5842a27b 5976 (Lisp_Object process, Lisp_Object current_group)
d0d6b7c5 5977{
d888760c 5978 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
e690ca94
KS
5979 {
5980 struct Lisp_Process *p;
5981
5982 p = XPROCESS (process);
5983 if (EQ (p->command, Qt)
60f0fb11 5984 && p->infd >= 0
e690ca94
KS
5985 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5986 {
60f0fb11
SM
5987 FD_SET (p->infd, &input_wait_mask);
5988 FD_SET (p->infd, &non_keyboard_wait_mask);
d888760c
GM
5989#ifdef WINDOWSNT
5990 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5991 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
a7ebc409 5992#else /* not WINDOWSNT */
d888760c 5993 tcflush (p->infd, TCIFLUSH);
a7ebc409 5994#endif /* not WINDOWSNT */
e690ca94
KS
5995 }
5996 p->command = Qnil;
5997 return process;
5998 }
d0d6b7c5
JB
5999#ifdef SIGCONT
6000 process_send_signal (process, SIGCONT, current_group, 0);
6001#else
a9a73d6c 6002 error ("No SIGCONT support");
d0d6b7c5
JB
6003#endif
6004 return process;
6005}
6006
6007DEFUN ("signal-process", Fsignal_process, Ssignal_process,
cdd5ea86
KS
6008 2, 2, "sProcess (name or number): \nnSignal code: ",
6009 doc: /* Send PROCESS the signal with code SIGCODE.
648f6edf 6010PROCESS may also be a number specifying the process id of the
cdd5ea86
KS
6011process to signal; in this case, the process need not be a child of
6012this Emacs.
fdb82f93 6013SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5842a27b 6014 (Lisp_Object process, Lisp_Object sigcode)
d0d6b7c5 6015{
6bfd98e7 6016 pid_t pid;
cdd5ea86
KS
6017
6018 if (INTEGERP (process))
6019 {
6bfd98e7
SM
6020 pid = XINT (process);
6021 goto got_it;
6022 }
6023
6024 if (FLOATP (process))
6025 {
648f6edf 6026 pid = (pid_t) XFLOAT_DATA (process);
cdd5ea86
KS
6027 goto got_it;
6028 }
6029
6030 if (STRINGP (process))
6031 {
6032 Lisp_Object tem;
6033 if (tem = Fget_process (process), NILP (tem))
6034 {
6bfd98e7
SM
6035 pid = XINT (Fstring_to_number (process, make_number (10)));
6036 if (pid > 0)
cdd5ea86
KS
6037 goto got_it;
6038 }
6039 process = tem;
6040 }
6041 else
6042 process = get_process (process);
177c0ea7 6043
cdd5ea86
KS
6044 if (NILP (process))
6045 return process;
6046
6047 CHECK_PROCESS (process);
6048 pid = XPROCESS (process)->pid;
6bfd98e7 6049 if (pid <= 0)
cdd5ea86
KS
6050 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6051
6052 got_it:
4766242d 6053
59324b1d 6054#define parse_signal(NAME, VALUE) \
05131107 6055 else if (!xstrcasecmp (name, NAME)) \
4766242d
RS
6056 XSETINT (sigcode, VALUE)
6057
6058 if (INTEGERP (sigcode))
6059 ;
6060 else
6061 {
6062 unsigned char *name;
6063
b7826503 6064 CHECK_SYMBOL (sigcode);
d5db4077 6065 name = SDATA (SYMBOL_NAME (sigcode));
4766242d 6066
ed3751c8 6067 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
675984ed
KS
6068 name += 3;
6069
4766242d
RS
6070 if (0)
6071 ;
59324b1d
KS
6072#ifdef SIGUSR1
6073 parse_signal ("usr1", SIGUSR1);
6074#endif
6075#ifdef SIGUSR2
6076 parse_signal ("usr2", SIGUSR2);
6077#endif
6078#ifdef SIGTERM
6079 parse_signal ("term", SIGTERM);
6080#endif
4766242d 6081#ifdef SIGHUP
59324b1d 6082 parse_signal ("hup", SIGHUP);
4766242d
RS
6083#endif
6084#ifdef SIGINT
59324b1d 6085 parse_signal ("int", SIGINT);
4766242d
RS
6086#endif
6087#ifdef SIGQUIT
59324b1d 6088 parse_signal ("quit", SIGQUIT);
4766242d
RS
6089#endif
6090#ifdef SIGILL
59324b1d 6091 parse_signal ("ill", SIGILL);
4766242d
RS
6092#endif
6093#ifdef SIGABRT
59324b1d 6094 parse_signal ("abrt", SIGABRT);
4766242d
RS
6095#endif
6096#ifdef SIGEMT
59324b1d 6097 parse_signal ("emt", SIGEMT);
4766242d
RS
6098#endif
6099#ifdef SIGKILL
59324b1d 6100 parse_signal ("kill", SIGKILL);
4766242d
RS
6101#endif
6102#ifdef SIGFPE
59324b1d 6103 parse_signal ("fpe", SIGFPE);
4766242d
RS
6104#endif
6105#ifdef SIGBUS
59324b1d 6106 parse_signal ("bus", SIGBUS);
4766242d
RS
6107#endif
6108#ifdef SIGSEGV
59324b1d 6109 parse_signal ("segv", SIGSEGV);
4766242d
RS
6110#endif
6111#ifdef SIGSYS
59324b1d 6112 parse_signal ("sys", SIGSYS);
4766242d
RS
6113#endif
6114#ifdef SIGPIPE
59324b1d 6115 parse_signal ("pipe", SIGPIPE);
4766242d
RS
6116#endif
6117#ifdef SIGALRM
59324b1d 6118 parse_signal ("alrm", SIGALRM);
4766242d
RS
6119#endif
6120#ifdef SIGURG
59324b1d 6121 parse_signal ("urg", SIGURG);
4766242d
RS
6122#endif
6123#ifdef SIGSTOP
59324b1d 6124 parse_signal ("stop", SIGSTOP);
4766242d
RS
6125#endif
6126#ifdef SIGTSTP
59324b1d 6127 parse_signal ("tstp", SIGTSTP);
4766242d
RS
6128#endif
6129#ifdef SIGCONT
59324b1d 6130 parse_signal ("cont", SIGCONT);
4766242d
RS
6131#endif
6132#ifdef SIGCHLD
59324b1d 6133 parse_signal ("chld", SIGCHLD);
4766242d
RS
6134#endif
6135#ifdef SIGTTIN
59324b1d 6136 parse_signal ("ttin", SIGTTIN);
4766242d
RS
6137#endif
6138#ifdef SIGTTOU
59324b1d 6139 parse_signal ("ttou", SIGTTOU);
4766242d
RS
6140#endif
6141#ifdef SIGIO
59324b1d 6142 parse_signal ("io", SIGIO);
4766242d
RS
6143#endif
6144#ifdef SIGXCPU
59324b1d 6145 parse_signal ("xcpu", SIGXCPU);
4766242d
RS
6146#endif
6147#ifdef SIGXFSZ
59324b1d 6148 parse_signal ("xfsz", SIGXFSZ);
4766242d
RS
6149#endif
6150#ifdef SIGVTALRM
59324b1d 6151 parse_signal ("vtalrm", SIGVTALRM);
4766242d
RS
6152#endif
6153#ifdef SIGPROF
59324b1d 6154 parse_signal ("prof", SIGPROF);
4766242d
RS
6155#endif
6156#ifdef SIGWINCH
59324b1d 6157 parse_signal ("winch", SIGWINCH);
4766242d
RS
6158#endif
6159#ifdef SIGINFO
59324b1d 6160 parse_signal ("info", SIGINFO);
4766242d
RS
6161#endif
6162 else
9fa195a2 6163 error ("Undefined signal name %s", name);
4766242d
RS
6164 }
6165
59324b1d 6166#undef parse_signal
4766242d 6167
6bfd98e7 6168 return make_number (kill (pid, XINT (sigcode)));
d0d6b7c5
JB
6169}
6170
6171DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
fdb82f93
PJ
6172 doc: /* Make PROCESS see end-of-file in its input.
6173EOF comes after any text already sent to it.
6174PROCESS may be a process, a buffer, the name of a process or buffer, or
6175nil, indicating the current buffer's process.
6176If PROCESS is a network connection, or is a process communicating
6177through a pipe (as opposed to a pty), then you cannot send any more
d888760c
GM
6178text to PROCESS after you call this function.
6179If PROCESS is a serial process, wait until all output written to the
6180process has been transmitted to the serial port. */)
5842a27b 6181 (Lisp_Object process)
d0d6b7c5
JB
6182{
6183 Lisp_Object proc;
de7fbd09 6184 struct coding_system *coding;
d0d6b7c5 6185
e690ca94
KS
6186 if (DATAGRAM_CONN_P (process))
6187 return process;
6188
d0d6b7c5 6189 proc = get_process (process);
60f0fb11 6190 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
577d03d5
RS
6191
6192 /* Make sure the process is really alive. */
6bfd98e7 6193 if (XPROCESS (proc)->raw_status_new)
577d03d5
RS
6194 update_status (XPROCESS (proc));
6195 if (! EQ (XPROCESS (proc)->status, Qrun))
d5db4077 6196 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
577d03d5 6197
de7fbd09
KH
6198 if (CODING_REQUIRE_FLUSHING (coding))
6199 {
6200 coding->mode |= CODING_MODE_LAST_BLOCK;
6201 send_process (proc, "", 0, Qnil);
6202 }
6203
60f0fb11 6204 if (XPROCESS (proc)->pty_flag)
4556b700 6205 send_process (proc, "\004", 1, Qnil);
a879ee6f 6206 else if (EQ (XPROCESS (proc)->type, Qserial))
d888760c 6207 {
a7ebc409 6208#ifndef WINDOWSNT
d888760c
GM
6209 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6210 error ("tcdrain() failed: %s", emacs_strerror (errno));
a7ebc409 6211#endif /* not WINDOWSNT */
d888760c
GM
6212 /* Do nothing on Windows because writes are blocking. */
6213 }
d0d6b7c5
JB
6214 else
6215 {
4525f571
RS
6216 int old_outfd, new_outfd;
6217
93853f3d 6218#ifdef HAVE_SHUTDOWN
02f55c4b
RS
6219 /* If this is a network connection, or socketpair is used
6220 for communication with the subprocess, call shutdown to cause EOF.
6221 (In some old system, shutdown to socketpair doesn't work.
6222 Then we just can't win.) */
a879ee6f 6223 if (EQ (XPROCESS (proc)->type, Qnetwork)
60f0fb11
SM
6224 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6225 shutdown (XPROCESS (proc)->outfd, 1);
02f55c4b 6226 /* In case of socketpair, outfd == infd, so don't close it. */
60f0fb11
SM
6227 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6228 emacs_close (XPROCESS (proc)->outfd);
93853f3d 6229#else /* not HAVE_SHUTDOWN */
60f0fb11 6230 emacs_close (XPROCESS (proc)->outfd);
93853f3d 6231#endif /* not HAVE_SHUTDOWN */
68c45bf0 6232 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
27448380
RS
6233 if (new_outfd < 0)
6234 abort ();
60f0fb11 6235 old_outfd = XPROCESS (proc)->outfd;
4525f571
RS
6236
6237 if (!proc_encode_coding_system[new_outfd])
6238 proc_encode_coding_system[new_outfd]
6239 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
72af86bd
AS
6240 memcpy (proc_encode_coding_system[new_outfd],
6241 proc_encode_coding_system[old_outfd],
6242 sizeof (struct coding_system));
6243 memset (proc_encode_coding_system[old_outfd], 0,
6244 sizeof (struct coding_system));
4525f571 6245
60f0fb11 6246 XPROCESS (proc)->outfd = new_outfd;
d0d6b7c5 6247 }
d0d6b7c5
JB
6248 return process;
6249}
d0d6b7c5 6250\f
3fed8ad5
GM
6251/* On receipt of a signal that a child status has changed, loop asking
6252 about children with changed statuses until the system says there
6253 are no more.
177c0ea7 6254
3fed8ad5
GM
6255 All we do is change the status; we do not run sentinels or print
6256 notifications. That is saved for the next time keyboard input is
6257 done, in order to avoid timing errors.
6258
6259 ** WARNING: this can be called during garbage collection.
6260 Therefore, it must not be fooled by the presence of mark bits in
6261 Lisp objects.
6262
6263 ** USG WARNING: Although it is not obvious from the documentation
6264 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6265 signal() before executing at least one wait(), otherwise the
6266 handler will be called again, resulting in an infinite loop. The
6267 relevant portion of the documentation reads "SIGCLD signals will be
6268 queued and the signal-catching function will be continually
6269 reentered until the queue is empty". Invoking signal() causes the
6270 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6b61353c
KH
6271 Inc.
6272
6273 ** Malloc WARNING: This should never call malloc either directly or
6274 indirectly; if it does, that is a bug */
d0d6b7c5 6275
a5cfdda8 6276#ifdef SIGCHLD
d0d6b7c5 6277SIGTYPE
d3da34e0 6278sigchld_handler (int signo)
d0d6b7c5
JB
6279{
6280 int old_errno = errno;
6281 Lisp_Object proc;
97ec208f 6282 struct Lisp_Process *p;
d0d6b7c5 6283
333f1b6f
JD
6284 SIGNAL_THREAD_CHECK (signo);
6285
d0d6b7c5
JB
6286 while (1)
6287 {
8e050977 6288 pid_t pid;
bba104c1 6289 int w;
d0d6b7c5
JB
6290 Lisp_Object tail;
6291
6292#ifdef WNOHANG
6293#ifndef WUNTRACED
6294#define WUNTRACED 0
6295#endif /* no WUNTRACED */
6296 /* Keep trying to get a status until we get a definitive result. */
e7d4a904 6297 do
63136da6 6298 {
29ed4d51
CY
6299 errno = 0;
6300 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
29ed4d51 6301 }
e7d4a904 6302 while (pid < 0 && errno == EINTR);
d0d6b7c5
JB
6303
6304 if (pid <= 0)
6305 {
3fed8ad5
GM
6306 /* PID == 0 means no processes found, PID == -1 means a real
6307 failure. We have done all our job, so return. */
d0d6b7c5 6308
d0d6b7c5
JB
6309 errno = old_errno;
6310 return;
6311 }
6312#else
6313 pid = wait (&w);
6314#endif /* no WNOHANG */
6315
6316 /* Find the process that signaled us, and record its status. */
6317
a5cfdda8 6318 /* The process can have been deleted by Fdelete_process. */
8e50cc2d 6319 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
a5cfdda8 6320 {
8e050977 6321 Lisp_Object xpid = XCAR (tail);
8e50cc2d
SM
6322 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6323 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
8e050977
CY
6324 {
6325 XSETCAR (tail, Qnil);
6326 goto sigchld_end_of_loop;
6327 }
a5cfdda8
KS
6328 }
6329
6330 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
d0d6b7c5 6331 p = 0;
8e50cc2d 6332 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
d0d6b7c5 6333 {
70949dac 6334 proc = XCDR (XCAR (tail));
d0d6b7c5 6335 p = XPROCESS (proc);
d888760c 6336 if (EQ (p->type, Qreal) && p->pid == pid)
d0d6b7c5
JB
6337 break;
6338 p = 0;
6339 }
6340
6341 /* Look for an asynchronous process whose pid hasn't been filled
6342 in yet. */
6343 if (p == 0)
8e50cc2d 6344 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
d0d6b7c5 6345 {
70949dac 6346 proc = XCDR (XCAR (tail));
d0d6b7c5 6347 p = XPROCESS (proc);
6bfd98e7 6348 if (p->pid == -1)
d0d6b7c5
JB
6349 break;
6350 p = 0;
6351 }
177c0ea7 6352
d0d6b7c5
JB
6353 /* Change the status of the process that was found. */
6354 if (p != 0)
6355 {
e98d950b 6356 int clear_desc_flag = 0;
177c0ea7 6357
60f0fb11 6358 p->tick = ++process_tick;
bba104c1 6359 p->raw_status = w;
6bfd98e7 6360 p->raw_status_new = 1;
177c0ea7 6361
d0d6b7c5 6362 /* If process has terminated, stop waiting for its output. */
e98d950b 6363 if ((WIFSIGNALED (w) || WIFEXITED (w))
60f0fb11 6364 && p->infd >= 0)
e98d950b
RS
6365 clear_desc_flag = 1;
6366
6367 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6368 if (clear_desc_flag)
6369 {
60f0fb11
SM
6370 FD_CLR (p->infd, &input_wait_mask);
6371 FD_CLR (p->infd, &non_keyboard_wait_mask);
e98d950b 6372 }
6be429b1 6373
214d6069 6374 /* Tell wait_reading_process_output that it needs to wake up and
6be429b1
JB
6375 look around. */
6376 if (input_available_clear_time)
6377 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
d0d6b7c5
JB
6378 }
6379
a5cfdda8
KS
6380 /* There was no asynchronous process found for that pid: we have
6381 a synchronous process. */
d0d6b7c5
JB
6382 else
6383 {
6384 synch_process_alive = 0;
6385
6386 /* Report the status of the synchronous process. */
6387 if (WIFEXITED (w))
6388 synch_process_retcode = WRETCODE (w);
6389 else if (WIFSIGNALED (w))
63136da6 6390 synch_process_termsig = WTERMSIG (w);
6be429b1 6391
214d6069 6392 /* Tell wait_reading_process_output that it needs to wake up and
6be429b1
JB
6393 look around. */
6394 if (input_available_clear_time)
6395 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
d0d6b7c5
JB
6396 }
6397
a5cfdda8
KS
6398 sigchld_end_of_loop:
6399 ;
6400
d0d6b7c5
JB
6401 /* On some systems, we must return right away.
6402 If any more processes want to signal us, we will
6403 get another signal.
6404 Otherwise (on systems that have WNOHANG), loop around
6405 to use up all the processes that have something to tell us. */
4e6277d8 6406#if (defined WINDOWSNT \
8a2a6032 6407 || (defined USG && !defined GNU_LINUX \
63136da6 6408 && !(defined HPUX && defined WNOHANG)))
d0d6b7c5
JB
6409 errno = old_errno;
6410 return;
6411#endif /* USG, but not HPUX with WNOHANG */
6412 }
6413}
a5cfdda8 6414#endif /* SIGCHLD */
d0d6b7c5
JB
6415\f
6416
6417static Lisp_Object
d3da34e0 6418exec_sentinel_unwind (Lisp_Object data)
d0d6b7c5 6419{
70949dac 6420 XPROCESS (XCAR (data))->sentinel = XCDR (data);
d0d6b7c5
JB
6421 return Qnil;
6422}
6423
3b9a3dfa 6424static Lisp_Object
d3da34e0 6425exec_sentinel_error_handler (Lisp_Object error)
3b9a3dfa
RS
6426{
6427 cmd_error_internal (error, "error in process sentinel: ");
6428 Vinhibit_quit = Qt;
6429 update_echo_area ();
833ba342 6430 Fsleep_for (make_number (2), Qnil);
8c983bf2 6431 return Qt;
3b9a3dfa
RS
6432}
6433
d0d6b7c5 6434static void
d3da34e0 6435exec_sentinel (Lisp_Object proc, Lisp_Object reason)
d0d6b7c5 6436{
dfc21838 6437 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
d0d6b7c5 6438 register struct Lisp_Process *p = XPROCESS (proc);
aed13378 6439 int count = SPECPDL_INDEX ();
4da2f5be 6440 int outer_running_asynch_code = running_asynch_code;
bbce7d72 6441 int waiting = waiting_for_user_input_p;
d0d6b7c5 6442
84af9896
RS
6443 if (inhibit_sentinels)
6444 return;
6445
dfc21838
RS
6446 /* No need to gcpro these, because all we do with them later
6447 is test them for EQness, and none of them should be a string. */
8fb3cf64 6448 odeactivate = Vdeactivate_mark;
dfc21838
RS
6449 XSETBUFFER (obuffer, current_buffer);
6450 okeymap = current_buffer->keymap;
6451
97e53006
SM
6452 /* There's no good reason to let sentinels change the current
6453 buffer, and many callers of accept-process-output, sit-for, and
6454 friends don't expect current-buffer to be changed from under them. */
d2630aef 6455 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
97e53006 6456
d0d6b7c5
JB
6457 sentinel = p->sentinel;
6458 if (NILP (sentinel))
6459 return;
6460
6461 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6462 assure that it gets restored no matter how the sentinel exits. */
6463 p->sentinel = Qnil;
6464 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6465 /* Inhibit quit so that random quits don't screw up a running filter. */
6466 specbind (Qinhibit_quit, Qt);
f00c449b 6467 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
3b9a3dfa 6468
4da2f5be
RS
6469 /* In case we get recursively called,
6470 and we already saved the match data nonrecursively,
6471 save the same match data in safely recursive fashion. */
6472 if (outer_running_asynch_code)
6473 {
6474 Lisp_Object tem;
89f2614d
KS
6475 tem = Fmatch_data (Qnil, Qnil, Qnil);
6476 restore_search_regs ();
6477 record_unwind_save_match_data ();
6478 Fset_match_data (tem, Qt);
4da2f5be
RS
6479 }
6480
6481 /* For speed, if a search happens within this code,
6482 save the match data in a special nonrecursive fashion. */
7074fde6 6483 running_asynch_code = 1;
4da2f5be 6484
3b9a3dfa
RS
6485 internal_condition_case_1 (read_process_output_call,
6486 Fcons (sentinel,
6487 Fcons (proc, Fcons (reason, Qnil))),
6488 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6489 exec_sentinel_error_handler);
4da2f5be
RS
6490
6491 /* If we saved the match data nonrecursively, restore it now. */
89f2614d 6492 restore_search_regs ();
4da2f5be 6493 running_asynch_code = outer_running_asynch_code;
8fb3cf64
KH
6494
6495 Vdeactivate_mark = odeactivate;
bbce7d72
RS
6496
6497 /* Restore waiting_for_user_input_p as it was
6498 when we were called, in case the filter clobbered it. */
6499 waiting_for_user_input_p = waiting;
6500
7973cfa8 6501#if 0
dfc21838
RS
6502 if (! EQ (Fcurrent_buffer (), obuffer)
6503 || ! EQ (current_buffer->keymap, okeymap))
7973cfa8 6504#endif
927e08be
RS
6505 /* But do it only if the caller is actually going to read events.
6506 Otherwise there's no need to make him wake up, and it could
7157b8fe 6507 cause trouble (for example it would make sit_for return). */
927e08be
RS
6508 if (waiting_for_user_input_p == -1)
6509 record_asynch_buffer_change ();
8fb3cf64 6510
2ea6d561 6511 unbind_to (count, Qnil);
d0d6b7c5
JB
6512}
6513
6514/* Report all recent events of a change in process status
6515 (either run the sentinel or output a message).
b50fe468
RS
6516 This is usually done while Emacs is waiting for keyboard input
6517 but can be done at other times. */
d0d6b7c5 6518
ff6daed3 6519static void
d3da34e0 6520status_notify (struct Lisp_Process *deleting_process)
d0d6b7c5
JB
6521{
6522 register Lisp_Object proc, buffer;
2e4149a8 6523 Lisp_Object tail, msg;
d0d6b7c5
JB
6524 struct gcpro gcpro1, gcpro2;
6525
2e4149a8
KH
6526 tail = Qnil;
6527 msg = Qnil;
d0d6b7c5
JB
6528 /* We need to gcpro tail; if read_process_output calls a filter
6529 which deletes a process and removes the cons to which tail points
6530 from Vprocess_alist, and then causes a GC, tail is an unprotected
6531 reference. */
6532 GCPRO2 (tail, msg);
6533
30623085
RS
6534 /* Set this now, so that if new processes are created by sentinels
6535 that we run, we get called again to handle their status changes. */
6536 update_tick = process_tick;
6537
99784d63 6538 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
d0d6b7c5 6539 {
30623085
RS
6540 Lisp_Object symbol;
6541 register struct Lisp_Process *p;
6542
99784d63 6543 proc = Fcdr (XCAR (tail));
30623085
RS
6544 p = XPROCESS (proc);
6545
60f0fb11 6546 if (p->tick != p->update_tick)
d0d6b7c5 6547 {
60f0fb11 6548 p->update_tick = p->tick;
d0d6b7c5 6549
30623085 6550 /* If process is still active, read any output that remains. */
4da2f5be 6551 while (! EQ (p->filter, Qt)
dd2a17ab 6552 && ! EQ (p->status, Qconnect)
e690ca94 6553 && ! EQ (p->status, Qlisten)
d888760c
GM
6554 /* Network or serial process not stopped: */
6555 && ! EQ (p->command, Qt)
60f0fb11 6556 && p->infd >= 0
ff6daed3 6557 && p != deleting_process
60f0fb11 6558 && read_process_output (proc, p->infd) > 0);
d0d6b7c5 6559
30623085 6560 buffer = p->buffer;
d0d6b7c5 6561
30623085 6562 /* Get the text to use for the message. */
6bfd98e7 6563 if (p->raw_status_new)
30623085 6564 update_status (p);
116c423c 6565 msg = status_message (p);
d0d6b7c5 6566
30623085
RS
6567 /* If process is terminated, deactivate it or delete it. */
6568 symbol = p->status;
6569 if (CONSP (p->status))
70949dac 6570 symbol = XCAR (p->status);
d0d6b7c5 6571
30623085
RS
6572 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6573 || EQ (symbol, Qclosed))
6574 {
6575 if (delete_exited_processes)
6576 remove_process (proc);
6577 else
6578 deactivate_process (proc);
6579 }
d0d6b7c5 6580
0ad61fe7
RS
6581 /* The actions above may have further incremented p->tick.
6582 So set p->update_tick again
6583 so that an error in the sentinel will not cause
6584 this code to be run again. */
60f0fb11 6585 p->update_tick = p->tick;
30623085
RS
6586 /* Now output the message suitably. */
6587 if (!NILP (p->sentinel))
6588 exec_sentinel (proc, msg);
6589 /* Don't bother with a message in the buffer
6590 when a process becomes runnable. */
6591 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6592 {
01f5787b 6593 Lisp_Object tem;
30623085 6594 struct buffer *old = current_buffer;
d8a2934e
RS
6595 int opoint, opoint_byte;
6596 int before, before_byte;
2e4149a8 6597
30623085
RS
6598 /* Avoid error if buffer is deleted
6599 (probably that's why the process is dead, too) */
6600 if (NILP (XBUFFER (buffer)->name))
6601 continue;
6602 Fset_buffer (buffer);
12ca5cdf 6603
6ec8bbd2 6604 opoint = PT;
d8a2934e 6605 opoint_byte = PT_BYTE;
30623085
RS
6606 /* Insert new output into buffer
6607 at the current end-of-output marker,
6608 thus preserving logical ordering of input and output. */
6609 if (XMARKER (p->mark)->buffer)
d8a2934e 6610 Fgoto_char (p->mark);
30623085 6611 else
d8a2934e 6612 SET_PT_BOTH (ZV, ZV_BYTE);
12ca5cdf
RS
6613
6614 before = PT;
d8a2934e 6615 before_byte = PT_BYTE;
30623085
RS
6616
6617 tem = current_buffer->read_only;
6618 current_buffer->read_only = Qnil;
6619 insert_string ("\nProcess ");
6620 Finsert (1, &p->name);
6621 insert_string (" ");
6622 Finsert (1, &msg);
6623 current_buffer->read_only = tem;
d8a2934e 6624 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
30623085 6625
12ca5cdf 6626 if (opoint >= before)
d8a2934e
RS
6627 SET_PT_BOTH (opoint + (PT - before),
6628 opoint_byte + (PT_BYTE - before_byte));
12ca5cdf 6629 else
d8a2934e 6630 SET_PT_BOTH (opoint, opoint_byte);
12ca5cdf 6631
30623085 6632 set_buffer_internal (old);
d0d6b7c5 6633 }
30623085
RS
6634 }
6635 } /* end for */
d0d6b7c5
JB
6636
6637 update_mode_lines++; /* in case buffers use %s in mode-line-format */
d0d6b7c5
JB
6638 UNGCPRO;
6639}
0fa1789e
KH
6640
6641\f
6642DEFUN ("set-process-coding-system", Fset_process_coding_system,
6643 Sset_process_coding_system, 1, 3, 0,
fdb82f93
PJ
6644 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6645DECODING will be used to decode subprocess output and ENCODING to
6646encode subprocess input. */)
5842a27b 6647 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
0fa1789e
KH
6648{
6649 register struct Lisp_Process *p;
6650
f3d9532b
JB
6651 CHECK_PROCESS (process);
6652 p = XPROCESS (process);
60f0fb11 6653 if (p->infd < 0)
d5db4077 6654 error ("Input file descriptor of %s closed", SDATA (p->name));
60f0fb11 6655 if (p->outfd < 0)
d5db4077 6656 error ("Output file descriptor of %s closed", SDATA (p->name));
03f04413
KH
6657 Fcheck_coding_system (decoding);
6658 Fcheck_coding_system (encoding);
76d812bb 6659 encoding = coding_inherit_eol_type (encoding, Qnil);
03f04413
KH
6660 p->decode_coding_system = decoding;
6661 p->encode_coding_system = encoding;
f3d9532b 6662 setup_process_coding_systems (process);
0fa1789e
KH
6663
6664 return Qnil;
6665}
6666
6667DEFUN ("process-coding-system",
6668 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
fdb82f93 6669 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
5842a27b 6670 (register Lisp_Object process)
0fa1789e 6671{
f3d9532b
JB
6672 CHECK_PROCESS (process);
6673 return Fcons (XPROCESS (process)->decode_coding_system,
6674 XPROCESS (process)->encode_coding_system);
0fa1789e 6675}
03f04413
KH
6676
6677DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6678 Sset_process_filter_multibyte, 2, 2, 0,
7392e23c
KS
6679 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6680If FLAG is non-nil, the filter is given multibyte strings.
6681If FLAG is nil, the filter is given unibyte strings. In this case,
03f04413
KH
6682all character code conversion except for end-of-line conversion is
6683suppressed. */)
5842a27b 6684 (Lisp_Object process, Lisp_Object flag)
03f04413
KH
6685{
6686 register struct Lisp_Process *p;
6687
f3d9532b
JB
6688 CHECK_PROCESS (process);
6689 p = XPROCESS (process);
5431bd6a
SM
6690 if (NILP (flag))
6691 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
f3d9532b 6692 setup_process_coding_systems (process);
03f04413
KH
6693
6694 return Qnil;
6695}
6696
6697DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6698 Sprocess_filter_multibyte_p, 1, 1, 0,
6699 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
5842a27b 6700 (Lisp_Object process)
03f04413
KH
6701{
6702 register struct Lisp_Process *p;
5431bd6a 6703 struct coding_system *coding;
03f04413 6704
f3d9532b
JB
6705 CHECK_PROCESS (process);
6706 p = XPROCESS (process);
5431bd6a
SM
6707 coding = proc_decode_coding_system[p->infd];
6708 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
03f04413
KH
6709}
6710
6711
d0d6b7c5 6712\f
cb768704 6713
994d9841
NR
6714static int add_gpm_wait_descriptor_called_flag;
6715
6716void
d3da34e0 6717add_gpm_wait_descriptor (int desc)
994d9841
NR
6718{
6719 if (! add_gpm_wait_descriptor_called_flag)
6720 FD_CLR (0, &input_wait_mask);
6721 add_gpm_wait_descriptor_called_flag = 1;
6722 FD_SET (desc, &input_wait_mask);
6723 FD_SET (desc, &gpm_wait_mask);
6724 if (desc > max_gpm_desc)
6725 max_gpm_desc = desc;
6726}
6727
994d9841 6728void
d3da34e0 6729delete_gpm_wait_descriptor (int desc)
994d9841
NR
6730{
6731 int fd;
6732 int lim = max_gpm_desc;
6733
6734 FD_CLR (desc, &input_wait_mask);
6735 FD_CLR (desc, &non_process_wait_mask);
6736
6737 if (desc == max_gpm_desc)
6738 for (fd = 0; fd < lim; fd++)
6739 if (FD_ISSET (fd, &input_wait_mask)
6740 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6741 && !FD_ISSET (fd, &non_process_wait_mask))
6742 max_gpm_desc = fd;
6743}
6744
a69281ff
RS
6745/* Return nonzero if *MASK has a bit set
6746 that corresponds to one of the keyboard input descriptors. */
6747
ff6daed3 6748static int
d3da34e0 6749keyboard_bit_set (fd_set *mask)
a69281ff
RS
6750{
6751 int fd;
6752
ee8e09af 6753 for (fd = 0; fd <= max_keyboard_desc; fd++)
a69281ff
RS
6754 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6755 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6756 return 1;
6757
6758 return 0;
6759}
934e2a68 6760
f388c88a 6761#else /* not subprocesses */
934e2a68 6762
f388c88a
EZ
6763/* Defined on msdos.c. */
6764extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6765 EMACS_TIME *);
934e2a68 6766
f388c88a
EZ
6767/* Implementation of wait_reading_process_output, assuming that there
6768 are no subprocesses. Used only by the MS-DOS build.
934e2a68 6769
f388c88a 6770 Wait for timeout to elapse and/or keyboard input to be available.
934e2a68 6771
f388c88a
EZ
6772 time_limit is:
6773 timeout in seconds, or
6774 zero for no limit, or
6775 -1 means gobble data immediately available but don't wait for any.
934e2a68 6776
f388c88a
EZ
6777 read_kbd is a Lisp_Object:
6778 0 to ignore keyboard input, or
6779 1 to return when input is available, or
6780 -1 means caller will actually read the input, so don't throw to
6781 the quit handler.
934e2a68 6782
f388c88a
EZ
6783 see full version for other parameters. We know that wait_proc will
6784 always be NULL, since `subprocesses' isn't defined.
934e2a68 6785
f388c88a
EZ
6786 do_display != 0 means redisplay should be done to show subprocess
6787 output that arrives.
934e2a68 6788
f388c88a
EZ
6789 Return true if we received input from any process. */
6790
6791int
1408902e
EZ
6792wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6793 int do_display,
6794 Lisp_Object wait_for_cell,
6795 struct Lisp_Process *wait_proc, int just_wait_proc)
d0d6b7c5 6796{
f388c88a
EZ
6797 register int nfds;
6798 EMACS_TIME end_time, timeout;
6799 SELECT_TYPE waitchannels;
6800 int xerrno;
d0d6b7c5 6801
f388c88a
EZ
6802 /* What does time_limit really mean? */
6803 if (time_limit || microsecs)
6804 {
6805 EMACS_GET_TIME (end_time);
6806 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6807 EMACS_ADD_TIME (end_time, end_time, timeout);
6808 }
84af9896 6809
f388c88a
EZ
6810 /* Turn off periodic alarms (in case they are in use)
6811 and then turn off any other atimers,
6812 because the select emulator uses alarms. */
6813 stop_polling ();
6814 turn_on_atimers (0);
d0d6b7c5 6815
f388c88a
EZ
6816 while (1)
6817 {
6818 int timeout_reduced_for_timers = 0;
dd2281ae 6819
f388c88a
EZ
6820 /* If calling from keyboard input, do not quit
6821 since we want to return C-g as an input character.
6822 Otherwise, do pending quit if requested. */
6823 if (read_kbd >= 0)
6824 QUIT;
bad49fc7 6825
f388c88a
EZ
6826 /* Exit now if the cell we're waiting for became non-nil. */
6827 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6828 break;
0a65b032 6829
bae8d137
RS
6830 /* Compute time from now till when time limit is up */
6831 /* Exit if already run out */
52fd88d3
EZ
6832 if (time_limit == -1)
6833 {
6834 /* -1 specified for timeout means
6835 gobble output available now
6836 but don't wait at all. */
6837
6838 EMACS_SET_SECS_USECS (timeout, 0, 0);
6839 }
6840 else if (time_limit || microsecs)
6720a7fb 6841 {
f694e5d2
KH
6842 EMACS_GET_TIME (timeout);
6843 EMACS_SUB_TIME (timeout, end_time, timeout);
6844 if (EMACS_TIME_NEG_P (timeout))
6720a7fb
JB
6845 break;
6846 }
52fd88d3
EZ
6847 else
6848 {
6849 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6850 }
6720a7fb 6851
bae8d137
RS
6852 /* If our caller will not immediately handle keyboard events,
6853 run timer events directly.
6854 (Callers that will immediately read keyboard events
6855 call timer_delay on their own.) */
f3fbd155 6856 if (NILP (wait_for_cell))
bae8d137
RS
6857 {
6858 EMACS_TIME timer_delay;
0a65b032 6859
9baacf76 6860 do
0a65b032 6861 {
9baacf76
GM
6862 int old_timers_run = timers_run;
6863 timer_delay = timer_check (1);
6864 if (timers_run != old_timers_run && do_display)
6865 /* We must retry, since a timer may have requeued itself
6866 and that could alter the time delay. */
3007ebfb 6867 redisplay_preserve_echo_area (14);
9baacf76
GM
6868 else
6869 break;
0a65b032 6870 }
9baacf76 6871 while (!detect_input_pending ());
0a65b032 6872
52fd88d3 6873 /* If there is unread keyboard input, also return. */
b89a415a 6874 if (read_kbd != 0
52fd88d3
EZ
6875 && requeued_events_pending_p ())
6876 break;
6877
f694e5d2 6878 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
bae8d137
RS
6879 {
6880 EMACS_TIME difference;
f694e5d2 6881 EMACS_SUB_TIME (difference, timer_delay, timeout);
bae8d137
RS
6882 if (EMACS_TIME_NEG_P (difference))
6883 {
f694e5d2 6884 timeout = timer_delay;
bae8d137
RS
6885 timeout_reduced_for_timers = 1;
6886 }
6887 }
6888 }
6889
6720a7fb
JB
6890 /* Cause C-g and alarm signals to take immediate action,
6891 and cause input available signals to zero out timeout. */
b89a415a 6892 if (read_kbd < 0)
6720a7fb
JB
6893 set_waiting_for_input (&timeout);
6894
0a65b032
RS
6895 /* Wait till there is something to do. */
6896
b89a415a 6897 if (! read_kbd && NILP (wait_for_cell))
0a65b032
RS
6898 FD_ZERO (&waitchannels);
6899 else
6900 FD_SET (0, &waitchannels);
6901
ff11dfa1 6902 /* If a frame has been newly mapped and needs updating,
6720a7fb 6903 reprocess its display stuff. */
5164ee8e 6904 if (frame_garbaged && do_display)
0a65b032
RS
6905 {
6906 clear_waiting_for_input ();
3007ebfb 6907 redisplay_preserve_echo_area (15);
b89a415a 6908 if (read_kbd < 0)
0a65b032
RS
6909 set_waiting_for_input (&timeout);
6910 }
6720a7fb 6911
b89a415a 6912 if (read_kbd && detect_input_pending ())
1861b214
RS
6913 {
6914 nfds = 0;
6915 FD_ZERO (&waitchannels);
6916 }
6917 else
6918 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6919 &timeout);
f694e5d2
KH
6920
6921 xerrno = errno;
6720a7fb
JB
6922
6923 /* Make C-g and alarm signals set flags again */
6924 clear_waiting_for_input ();
6925
6926 /* If we woke up due to SIGWINCH, actually change size now. */
2b653806 6927 do_pending_window_change (0);
6720a7fb 6928
f694e5d2
KH
6929 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6930 /* We waited the full specified time, so return now. */
6931 break;
6932
6720a7fb
JB
6933 if (nfds == -1)
6934 {
6935 /* If the system call was interrupted, then go around the
6936 loop again. */
f694e5d2 6937 if (xerrno == EINTR)
8db121c4 6938 FD_ZERO (&waitchannels);
f694e5d2 6939 else
68c45bf0 6940 error ("select error: %s", emacs_strerror (xerrno));
6720a7fb 6941 }
6720a7fb 6942
f694e5d2
KH
6943 /* Check for keyboard input */
6944
b89a415a 6945 if (read_kbd
78c1afb6 6946 && detect_input_pending_run_timers (do_display))
f694e5d2 6947 {
78c1afb6 6948 swallow_events (do_display);
f694e5d2 6949 if (detect_input_pending_run_timers (do_display))
a2fab450 6950 break;
78c1afb6
EZ
6951 }
6952
52fd88d3 6953 /* If there is unread keyboard input, also return. */
b89a415a 6954 if (read_kbd
52fd88d3
EZ
6955 && requeued_events_pending_p ())
6956 break;
6957
f854a00b
RS
6958 /* If wait_for_cell. check for keyboard input
6959 but don't run any timers.
6960 ??? (It seems wrong to me to check for keyboard
6961 input at all when wait_for_cell, but the code
6962 has been this way since July 1994.
6963 Try changing this after version 19.31.) */
f3fbd155 6964 if (! NILP (wait_for_cell)
f854a00b
RS
6965 && detect_input_pending ())
6966 {
6967 swallow_events (do_display);
6968 if (detect_input_pending ())
6969 break;
6970 }
6971
0a65b032 6972 /* Exit now if the cell we're waiting for became non-nil. */
f3fbd155 6973 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
0a65b032 6974 break;
6720a7fb
JB
6975 }
6976
a87b802f
JB
6977 start_polling ();
6978
6720a7fb
JB
6979 return 0;
6980}
6981
f388c88a
EZ
6982#endif /* not subprocesses */
6983
6984/* The following functions are needed even if async subprocesses are
6985 not supported. Some of them are no-op stubs in that case. */
6720a7fb 6986
01faa934
DN
6987/* Add DESC to the set of keyboard input descriptors. */
6988
6989void
6990add_keyboard_wait_descriptor (int desc)
6991{
20477505 6992#ifdef subprocesses
01faa934
DN
6993 FD_SET (desc, &input_wait_mask);
6994 FD_SET (desc, &non_process_wait_mask);
6995 if (desc > max_keyboard_desc)
6996 max_keyboard_desc = desc;
20477505 6997#endif
01faa934
DN
6998}
6999
7000/* From now on, do not expect DESC to give keyboard input. */
7001
7002void
7003delete_keyboard_wait_descriptor (int desc)
7004{
7005#ifdef subprocesses
7006 int fd;
7007 int lim = max_keyboard_desc;
7008
7009 FD_CLR (desc, &input_wait_mask);
7010 FD_CLR (desc, &non_process_wait_mask);
7011
7012 if (desc == max_keyboard_desc)
7013 for (fd = 0; fd < lim; fd++)
7014 if (FD_ISSET (fd, &input_wait_mask)
7015 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7016 && !FD_ISSET (fd, &gpm_wait_mask))
7017 max_keyboard_desc = fd;
7018#endif /* subprocesses */
7019}
7020
fc549af9
EZ
7021/* Setup coding systems of PROCESS. */
7022
7023void
7024setup_process_coding_systems (Lisp_Object process)
7025{
7026#ifdef subprocesses
7027 struct Lisp_Process *p = XPROCESS (process);
7028 int inch = p->infd;
7029 int outch = p->outfd;
7030 Lisp_Object coding_system;
7031
7032 if (inch < 0 || outch < 0)
7033 return;
7034
7035 if (!proc_decode_coding_system[inch])
7036 proc_decode_coding_system[inch]
7037 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7038 coding_system = p->decode_coding_system;
7039 if (! NILP (p->filter))
7040 ;
7041 else if (BUFFERP (p->buffer))
7042 {
7043 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7044 coding_system = raw_text_coding_system (coding_system);
7045 }
7046 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7047
7048 if (!proc_encode_coding_system[outch])
7049 proc_encode_coding_system[outch]
7050 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7051 setup_coding_system (p->encode_coding_system,
7052 proc_encode_coding_system[outch]);
7053#endif
7054}
7055
7056/* Close all descriptors currently in use for communication
7057 with subprocess. This is used in a newly-forked subprocess
7058 to get rid of irrelevant descriptors. */
7059
7060void
7061close_process_descs (void)
7062{
7063#ifndef DOS_NT
7064 int i;
7065 for (i = 0; i < MAXDESC; i++)
7066 {
7067 Lisp_Object process;
7068 process = chan_process[i];
7069 if (!NILP (process))
7070 {
7071 int in = XPROCESS (process)->infd;
7072 int out = XPROCESS (process)->outfd;
7073 if (in >= 0)
7074 emacs_close (in);
7075 if (out >= 0 && in != out)
7076 emacs_close (out);
7077 }
7078 }
7079#endif
7080}
7081
6720a7fb 7082DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
f388c88a
EZ
7083 doc: /* Return the (or a) process associated with BUFFER.
7084BUFFER may be a buffer or the name of one. */)
7085 (register Lisp_Object buffer)
6720a7fb 7086{
f388c88a
EZ
7087#ifdef subprocesses
7088 register Lisp_Object buf, tail, proc;
7089
7090 if (NILP (buffer)) return Qnil;
7091 buf = Fget_buffer (buffer);
7092 if (NILP (buf)) return Qnil;
7093
7094 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7095 {
7096 proc = Fcdr (XCAR (tail));
7097 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7098 return proc;
7099 }
7100#endif /* subprocesses */
6720a7fb
JB
7101 return Qnil;
7102}
7103
52a1b894 7104DEFUN ("process-inherit-coding-system-flag",
fdb82f93
PJ
7105 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7106 1, 1, 0,
f388c88a
EZ
7107 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7108If this flag is t, `buffer-file-coding-system' of the buffer
7109associated with PROCESS will inherit the coding system used to decode
7110the process output. */)
5842a27b 7111 (register Lisp_Object process)
52a1b894 7112{
f388c88a
EZ
7113#ifdef subprocesses
7114 CHECK_PROCESS (process);
7115 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7116#else
52a1b894
EZ
7117 /* Ignore the argument and return the value of
7118 inherit-process-coding-system. */
7119 return inherit_process_coding_system ? Qt : Qnil;
f388c88a 7120#endif
52a1b894
EZ
7121}
7122
6720a7fb 7123/* Kill all processes associated with `buffer'.
f388c88a 7124 If `buffer' is nil, kill all processes */
6720a7fb 7125
d9bb0c32 7126void
f388c88a 7127kill_buffer_processes (Lisp_Object buffer)
6720a7fb 7128{
f388c88a
EZ
7129#ifdef subprocesses
7130 Lisp_Object tail, proc;
7131
7132 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7133 {
7134 proc = XCDR (XCAR (tail));
7135 if (PROCESSP (proc)
7136 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7137 {
7138 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7139 Fdelete_process (proc);
7140 else if (XPROCESS (proc)->infd >= 0)
7141 process_send_signal (proc, SIGHUP, Qnil, 1);
7142 }
7143 }
7144#else /* subprocesses */
7145 /* Since we have no subprocesses, this does nothing. */
7146#endif /* subprocesses */
6720a7fb
JB
7147}
7148
77defa9a
EZ
7149DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7150 0, 0, 0,
7151 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7152This is intended for use by asynchronous process output filters and sentinels. */)
7153 (void)
7154{
7155#ifdef subprocesses
7156 return (waiting_for_user_input_p ? Qt : Qnil);
7157#else
7158 return Qnil;
7159#endif
7160}
7161
d568829b
EZ
7162/* Stop reading input from keyboard sources. */
7163
7164void
7165hold_keyboard_input (void)
7166{
7167 kbd_is_on_hold = 1;
7168}
7169
7170/* Resume reading input from keyboard sources. */
7171
7172void
7173unhold_keyboard_input (void)
7174{
7175 kbd_is_on_hold = 0;
7176}
7177
7178/* Return non-zero if keyboard input is on hold, zero otherwise. */
7179
7180int
7181kbd_on_hold_p (void)
7182{
7183 return kbd_is_on_hold;
7184}
7185
f388c88a
EZ
7186\f
7187/* Enumeration of and access to system processes a-la ps(1). */
7188
934e2a68
EZ
7189DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7190 0, 0, 0,
7191 doc: /* Return a list of numerical process IDs of all running processes.
7192If this functionality is unsupported, return nil.
7193
f388c88a
EZ
7194See `process-attributes' for getting attributes of a process given its ID. */)
7195 (void)
7196{
7197 return list_system_processes ();
7198}
7199
7200DEFUN ("process-attributes", Fprocess_attributes,
7201 Sprocess_attributes, 1, 1, 0,
7202 doc: /* Return attributes of the process given by its PID, a number.
7203
7204Value is an alist where each element is a cons cell of the form
7205
7206 \(KEY . VALUE)
7207
7208If this functionality is unsupported, the value is nil.
7209
7210See `list-system-processes' for getting a list of all process IDs.
7211
7212The KEYs of the attributes that this function may return are listed
7213below, together with the type of the associated VALUE (in parentheses).
7214Not all platforms support all of these attributes; unsupported
7215attributes will not appear in the returned alist.
7216Unless explicitly indicated otherwise, numbers can have either
7217integer or floating point values.
7218
7219 euid -- Effective user User ID of the process (number)
7220 user -- User name corresponding to euid (string)
7221 egid -- Effective user Group ID of the process (number)
7222 group -- Group name corresponding to egid (string)
7223 comm -- Command name (executable name only) (string)
7224 state -- Process state code, such as "S", "R", or "T" (string)
7225 ppid -- Parent process ID (number)
7226 pgrp -- Process group ID (number)
7227 sess -- Session ID, i.e. process ID of session leader (number)
7228 ttname -- Controlling tty name (string)
7229 tpgid -- ID of foreground process group on the process's tty (number)
7230 minflt -- number of minor page faults (number)
7231 majflt -- number of major page faults (number)
7232 cminflt -- cumulative number of minor page faults (number)
7233 cmajflt -- cumulative number of major page faults (number)
7234 utime -- user time used by the process, in the (HIGH LOW USEC) format
7235 stime -- system time used by the process, in the (HIGH LOW USEC) format
7236 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7237 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7238 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7239 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7240 pri -- priority of the process (number)
7241 nice -- nice value of the process (number)
7242 thcount -- process thread count (number)
7243 start -- time the process started, in the (HIGH LOW USEC) format
7244 vsize -- virtual memory size of the process in KB's (number)
7245 rss -- resident set size of the process in KB's (number)
7246 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7247 pcpu -- percents of CPU time used by the process (floating-point number)
7248 pmem -- percents of total physical memory used by process's resident set
7249 (floating-point number)
7250 args -- command line which invoked the process (string). */)
7251 ( Lisp_Object pid)
7252{
7253 return system_process_attributes (pid);
7254}
7255
7256\f
7257void
7258init_process (void)
7259{
7260#ifdef subprocesses
7261 register int i;
7262
7263 inhibit_sentinels = 0;
7264
7265#ifdef SIGCHLD
7266#ifndef CANNOT_DUMP
7267 if (! noninteractive || initialized)
7268#endif
7269 signal (SIGCHLD, sigchld_handler);
7270#endif
7271
7272 FD_ZERO (&input_wait_mask);
7273 FD_ZERO (&non_keyboard_wait_mask);
7274 FD_ZERO (&non_process_wait_mask);
7275 max_process_desc = 0;
7276
7277#ifdef NON_BLOCKING_CONNECT
7278 FD_ZERO (&connect_wait_mask);
7279 num_pending_connects = 0;
7280#endif
7281
7282#ifdef ADAPTIVE_READ_BUFFERING
7283 process_output_delay_count = 0;
7284 process_output_skip = 0;
7285#endif
7286
7287 /* Don't do this, it caused infinite select loops. The display
7288 method should call add_keyboard_wait_descriptor on stdin if it
7289 needs that. */
7290#if 0
7291 FD_SET (0, &input_wait_mask);
7292#endif
7293
7294 Vprocess_alist = Qnil;
7295#ifdef SIGCHLD
7296 deleted_pid_list = Qnil;
7297#endif
7298 for (i = 0; i < MAXDESC; i++)
7299 {
7300 chan_process[i] = Qnil;
7301 proc_buffered_char[i] = -1;
7302 }
7303 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7304 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7305#ifdef DATAGRAM_SOCKETS
7306 memset (datagram_address, 0, sizeof datagram_address);
7307#endif
7308
f388c88a
EZ
7309 {
7310 Lisp_Object subfeatures = Qnil;
7311 const struct socket_options *sopt;
7312
7313#define ADD_SUBFEATURE(key, val) \
7314 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7315
7316#ifdef NON_BLOCKING_CONNECT
7317 ADD_SUBFEATURE (QCnowait, Qt);
7318#endif
7319#ifdef DATAGRAM_SOCKETS
7320 ADD_SUBFEATURE (QCtype, Qdatagram);
7321#endif
7322#ifdef HAVE_SEQPACKET
7323 ADD_SUBFEATURE (QCtype, Qseqpacket);
7324#endif
7325#ifdef HAVE_LOCAL_SOCKETS
7326 ADD_SUBFEATURE (QCfamily, Qlocal);
7327#endif
7328 ADD_SUBFEATURE (QCfamily, Qipv4);
7329#ifdef AF_INET6
7330 ADD_SUBFEATURE (QCfamily, Qipv6);
7331#endif
7332#ifdef HAVE_GETSOCKNAME
7333 ADD_SUBFEATURE (QCservice, Qt);
7334#endif
7335#if defined(O_NONBLOCK) || defined(O_NDELAY)
7336 ADD_SUBFEATURE (QCserver, Qt);
7337#endif
7338
7339 for (sopt = socket_options; sopt->name; sopt++)
7340 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7341
7342 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7343 }
f388c88a
EZ
7344
7345#if defined (DARWIN_OS)
7346 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7347 processes. As such, we only change the default value. */
7348 if (initialized)
7349 {
8ea90aa3 7350 const char *release = get_operating_system_release ();
f388c88a
EZ
7351 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7352 && release[1] == '.')) {
7353 Vprocess_connection_type = Qnil;
7354 }
7355 }
7356#endif
7357#endif /* subprocesses */
7358 kbd_is_on_hold = 0;
7359}
7360
7361void
7362syms_of_process (void)
7363{
7364#ifdef subprocesses
7365
7366 Qprocessp = intern_c_string ("processp");
7367 staticpro (&Qprocessp);
7368 Qrun = intern_c_string ("run");
7369 staticpro (&Qrun);
7370 Qstop = intern_c_string ("stop");
7371 staticpro (&Qstop);
7372 Qsignal = intern_c_string ("signal");
7373 staticpro (&Qsignal);
7374
7375 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7376 here again.
934e2a68 7377
f388c88a
EZ
7378 Qexit = intern_c_string ("exit");
7379 staticpro (&Qexit); */
934e2a68 7380
f388c88a
EZ
7381 Qopen = intern_c_string ("open");
7382 staticpro (&Qopen);
7383 Qclosed = intern_c_string ("closed");
7384 staticpro (&Qclosed);
7385 Qconnect = intern_c_string ("connect");
7386 staticpro (&Qconnect);
7387 Qfailed = intern_c_string ("failed");
7388 staticpro (&Qfailed);
7389 Qlisten = intern_c_string ("listen");
7390 staticpro (&Qlisten);
7391 Qlocal = intern_c_string ("local");
7392 staticpro (&Qlocal);
7393 Qipv4 = intern_c_string ("ipv4");
7394 staticpro (&Qipv4);
7395#ifdef AF_INET6
7396 Qipv6 = intern_c_string ("ipv6");
7397 staticpro (&Qipv6);
7398#endif
7399 Qdatagram = intern_c_string ("datagram");
7400 staticpro (&Qdatagram);
7401 Qseqpacket = intern_c_string ("seqpacket");
7402 staticpro (&Qseqpacket);
934e2a68 7403
f388c88a
EZ
7404 QCport = intern_c_string (":port");
7405 staticpro (&QCport);
7406 QCspeed = intern_c_string (":speed");
7407 staticpro (&QCspeed);
7408 QCprocess = intern_c_string (":process");
7409 staticpro (&QCprocess);
934e2a68 7410
f388c88a
EZ
7411 QCbytesize = intern_c_string (":bytesize");
7412 staticpro (&QCbytesize);
7413 QCstopbits = intern_c_string (":stopbits");
7414 staticpro (&QCstopbits);
7415 QCparity = intern_c_string (":parity");
7416 staticpro (&QCparity);
7417 Qodd = intern_c_string ("odd");
7418 staticpro (&Qodd);
7419 Qeven = intern_c_string ("even");
7420 staticpro (&Qeven);
7421 QCflowcontrol = intern_c_string (":flowcontrol");
7422 staticpro (&QCflowcontrol);
7423 Qhw = intern_c_string ("hw");
7424 staticpro (&Qhw);
7425 Qsw = intern_c_string ("sw");
7426 staticpro (&Qsw);
7427 QCsummary = intern_c_string (":summary");
7428 staticpro (&QCsummary);
934e2a68 7429
f388c88a
EZ
7430 Qreal = intern_c_string ("real");
7431 staticpro (&Qreal);
7432 Qnetwork = intern_c_string ("network");
7433 staticpro (&Qnetwork);
7434 Qserial = intern_c_string ("serial");
7435 staticpro (&Qserial);
7436 QCbuffer = intern_c_string (":buffer");
7437 staticpro (&QCbuffer);
7438 QChost = intern_c_string (":host");
7439 staticpro (&QChost);
7440 QCservice = intern_c_string (":service");
7441 staticpro (&QCservice);
7442 QClocal = intern_c_string (":local");
7443 staticpro (&QClocal);
7444 QCremote = intern_c_string (":remote");
7445 staticpro (&QCremote);
7446 QCcoding = intern_c_string (":coding");
7447 staticpro (&QCcoding);
7448 QCserver = intern_c_string (":server");
7449 staticpro (&QCserver);
7450 QCnowait = intern_c_string (":nowait");
7451 staticpro (&QCnowait);
7452 QCsentinel = intern_c_string (":sentinel");
7453 staticpro (&QCsentinel);
7454 QClog = intern_c_string (":log");
7455 staticpro (&QClog);
7456 QCnoquery = intern_c_string (":noquery");
7457 staticpro (&QCnoquery);
7458 QCstop = intern_c_string (":stop");
7459 staticpro (&QCstop);
7460 QCoptions = intern_c_string (":options");
7461 staticpro (&QCoptions);
7462 QCplist = intern_c_string (":plist");
7463 staticpro (&QCplist);
934e2a68 7464
f388c88a
EZ
7465 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7466 staticpro (&Qlast_nonmenu_event);
934e2a68 7467
f388c88a
EZ
7468 staticpro (&Vprocess_alist);
7469#ifdef SIGCHLD
7470 staticpro (&deleted_pid_list);
7471#endif
934e2a68 7472
f388c88a 7473#endif /* subprocesses */
6720a7fb 7474
d67b4f80 7475 QCname = intern_c_string (":name");
8c57b2e5 7476 staticpro (&QCname);
d67b4f80 7477 QCtype = intern_c_string (":type");
6a1bab0e 7478 staticpro (&QCtype);
f388c88a 7479
d67b4f80 7480 Qeuid = intern_c_string ("euid");
6a1bab0e 7481 staticpro (&Qeuid);
d67b4f80 7482 Qegid = intern_c_string ("egid");
6a1bab0e 7483 staticpro (&Qegid);
d67b4f80 7484 Quser = intern_c_string ("user");
6a1bab0e 7485 staticpro (&Quser);
d67b4f80 7486 Qgroup = intern_c_string ("group");
6a1bab0e 7487 staticpro (&Qgroup);
d67b4f80 7488 Qcomm = intern_c_string ("comm");
6a1bab0e 7489 staticpro (&Qcomm);
d67b4f80 7490 Qstate = intern_c_string ("state");
6a1bab0e 7491 staticpro (&Qstate);
d67b4f80 7492 Qppid = intern_c_string ("ppid");
6a1bab0e 7493 staticpro (&Qppid);
d67b4f80 7494 Qpgrp = intern_c_string ("pgrp");
6a1bab0e 7495 staticpro (&Qpgrp);
d67b4f80 7496 Qsess = intern_c_string ("sess");
6a1bab0e 7497 staticpro (&Qsess);
d67b4f80 7498 Qttname = intern_c_string ("ttname");
6a1bab0e 7499 staticpro (&Qttname);
d67b4f80 7500 Qtpgid = intern_c_string ("tpgid");
6a1bab0e 7501 staticpro (&Qtpgid);
d67b4f80 7502 Qminflt = intern_c_string ("minflt");
6a1bab0e 7503 staticpro (&Qminflt);
d67b4f80 7504 Qmajflt = intern_c_string ("majflt");
6a1bab0e 7505 staticpro (&Qmajflt);
d67b4f80 7506 Qcminflt = intern_c_string ("cminflt");
6a1bab0e 7507 staticpro (&Qcminflt);
d67b4f80 7508 Qcmajflt = intern_c_string ("cmajflt");
6a1bab0e 7509 staticpro (&Qcmajflt);
d67b4f80 7510 Qutime = intern_c_string ("utime");
6a1bab0e 7511 staticpro (&Qutime);
d67b4f80 7512 Qstime = intern_c_string ("stime");
6a1bab0e 7513 staticpro (&Qstime);
d67b4f80 7514 Qtime = intern_c_string ("time");
6a1bab0e 7515 staticpro (&Qtime);
d67b4f80 7516 Qcutime = intern_c_string ("cutime");
6a1bab0e 7517 staticpro (&Qcutime);
d67b4f80 7518 Qcstime = intern_c_string ("cstime");
6a1bab0e 7519 staticpro (&Qcstime);
d67b4f80 7520 Qctime = intern_c_string ("ctime");
6a1bab0e 7521 staticpro (&Qctime);
d67b4f80 7522 Qpri = intern_c_string ("pri");
6a1bab0e 7523 staticpro (&Qpri);
d67b4f80 7524 Qnice = intern_c_string ("nice");
6a1bab0e 7525 staticpro (&Qnice);
d67b4f80 7526 Qthcount = intern_c_string ("thcount");
6a1bab0e 7527 staticpro (&Qthcount);
d67b4f80 7528 Qstart = intern_c_string ("start");
6a1bab0e 7529 staticpro (&Qstart);
d67b4f80 7530 Qvsize = intern_c_string ("vsize");
6a1bab0e 7531 staticpro (&Qvsize);
d67b4f80 7532 Qrss = intern_c_string ("rss");
6a1bab0e 7533 staticpro (&Qrss);
d67b4f80 7534 Qetime = intern_c_string ("etime");
6a1bab0e 7535 staticpro (&Qetime);
d67b4f80 7536 Qpcpu = intern_c_string ("pcpu");
6a1bab0e 7537 staticpro (&Qpcpu);
d67b4f80 7538 Qpmem = intern_c_string ("pmem");
6a1bab0e 7539 staticpro (&Qpmem);
d67b4f80 7540 Qargs = intern_c_string ("args");
6a1bab0e 7541 staticpro (&Qargs);
9057ff80 7542
f388c88a
EZ
7543 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7544 doc: /* *Non-nil means delete processes immediately when they exit.
7545A value of nil means don't delete them until `list-processes' is run. */);
7546
7547 delete_exited_processes = 1;
7548
462aa963 7549#ifdef subprocesses
f388c88a
EZ
7550 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7551 doc: /* Control type of device used to communicate with subprocesses.
7552Values are nil to use a pipe, or t or `pty' to use a pty.
7553The value has no effect if the system has no ptys or if all ptys are busy:
7554then a pipe is used in any case.
7555The value takes effect when `start-process' is called. */);
7556 Vprocess_connection_type = Qt;
7557
7558#ifdef ADAPTIVE_READ_BUFFERING
7559 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7560 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7561On some systems, when Emacs reads the output from a subprocess, the output data
7562is read in very small blocks, potentially resulting in very poor performance.
7563This behavior can be remedied to some extent by setting this variable to a
7564non-nil value, as it will automatically delay reading from such processes, to
7565allow them to produce more output before Emacs tries to read it.
7566If the value is t, the delay is reset after each write to the process; any other
7567non-nil value means that the delay is not reset on write.
7568The variable takes effect when `start-process' is called. */);
7569 Vprocess_adaptive_read_buffering = Qt;
7570#endif
7571
7572 defsubr (&Sprocessp);
7573 defsubr (&Sget_process);
7574 defsubr (&Sdelete_process);
7575 defsubr (&Sprocess_status);
7576 defsubr (&Sprocess_exit_status);
7577 defsubr (&Sprocess_id);
7578 defsubr (&Sprocess_name);
7579 defsubr (&Sprocess_tty_name);
7580 defsubr (&Sprocess_command);
7581 defsubr (&Sset_process_buffer);
7582 defsubr (&Sprocess_buffer);
7583 defsubr (&Sprocess_mark);
7584 defsubr (&Sset_process_filter);
7585 defsubr (&Sprocess_filter);
7586 defsubr (&Sset_process_sentinel);
7587 defsubr (&Sprocess_sentinel);
7588 defsubr (&Sset_process_window_size);
7589 defsubr (&Sset_process_inherit_coding_system_flag);
7590 defsubr (&Sset_process_query_on_exit_flag);
7591 defsubr (&Sprocess_query_on_exit_flag);
7592 defsubr (&Sprocess_contact);
7593 defsubr (&Sprocess_plist);
7594 defsubr (&Sset_process_plist);
7595 defsubr (&Slist_processes);
7596 defsubr (&Sprocess_list);
7597 defsubr (&Sstart_process);
f388c88a
EZ
7598 defsubr (&Sserial_process_configure);
7599 defsubr (&Smake_serial_process);
f388c88a
EZ
7600 defsubr (&Sset_network_process_option);
7601 defsubr (&Smake_network_process);
7602 defsubr (&Sformat_network_address);
fce70521 7603#if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
f388c88a
EZ
7604#ifdef SIOCGIFCONF
7605 defsubr (&Snetwork_interface_list);
7606#endif
7607#if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7608 defsubr (&Snetwork_interface_info);
7609#endif
fce70521 7610#endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
f388c88a
EZ
7611#ifdef DATAGRAM_SOCKETS
7612 defsubr (&Sprocess_datagram_address);
7613 defsubr (&Sset_process_datagram_address);
7614#endif
7615 defsubr (&Saccept_process_output);
7616 defsubr (&Sprocess_send_region);
7617 defsubr (&Sprocess_send_string);
7618 defsubr (&Sinterrupt_process);
7619 defsubr (&Skill_process);
7620 defsubr (&Squit_process);
7621 defsubr (&Sstop_process);
7622 defsubr (&Scontinue_process);
7623 defsubr (&Sprocess_running_child_p);
7624 defsubr (&Sprocess_send_eof);
7625 defsubr (&Ssignal_process);
7626 defsubr (&Swaiting_for_user_input_p);
7627 defsubr (&Sprocess_type);
7628 defsubr (&Sset_process_coding_system);
7629 defsubr (&Sprocess_coding_system);
7630 defsubr (&Sset_process_filter_multibyte);
7631 defsubr (&Sprocess_filter_multibyte_p);
7632
7633#endif /* subprocesses */
7634
6720a7fb 7635 defsubr (&Sget_buffer_process);
52a1b894 7636 defsubr (&Sprocess_inherit_coding_system_flag);
934e2a68 7637 defsubr (&Slist_system_processes);
a20878b6 7638 defsubr (&Sprocess_attributes);
6720a7fb
JB
7639}
7640
6b61353c
KH
7641/* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7642 (do not change this comment) */