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