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