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