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