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