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