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