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