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