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