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