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