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