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