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